JavaBean:用于传递数据,拥有与数据相关的逻辑处理

JSP:从Model接收数据并生成HTML

Servlet:接收HTTP请求并控制Model和View

jdbc:用于驱动连接

一、【建立数据库】

在mysql中新建一个名为course的数据库,并在其中新建一个course数据表,包含四个字段,ID,classname,classroom,teacher

二、【新建web项目

1. eclipse新建一个名为course的Dynamic Web Project

修改class的默认输出目录为:WebContent/WEB-INF/classes,勾选自动生成web.xml

2. 将连接mysql的驱动jar包(

二、【新建web项目

1. eclipse新建一个名为kechengguanlli的Dynamic Web Project

修改class的默认输出目录为:WebContent/WEB-INF/classes,勾选自动生成web.xml

2. 将连接mysql的驱动jar包(mysql-connector-java-5.1.7-bin.jar)copy到WEB-INF下的lib目录下

3.  新建7个包

4. 新建类,java类放在对应包中,jsp页面放在WebContent目录下,替换web.xml中内容

package com.hjf.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List; import com.hjf.entity.Course;
import com.hjf.util.DBUtil; /**
* 璇剧▼Dao
* Dao灞傛搷浣滄暟鎹�
* @author Hu
*
*/
public class CourseDao { /**
* 娣诲姞
* @param course
* @return
*/
public boolean add(Course course) {
String sql = "insert into course(name, teacher, classroom) values('" + course.getName() + "','" + course.getTeacher() + "','" + course.getClassroom() + "')";
//鍒涘缓鏁版嵁搴撻摼鎺�
Connection conn = DBUtil.getConn();
Statement state = null;
boolean f = false;
int a = 0; try {
state = conn.createStatement();
state.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
//鍏抽棴杩炴帴
DBUtil.close(state, conn);
} if (a > 0) {
f = true;
}
return f;
} /**
* 鍒犻櫎
*
* @param id
* @return
*/
public boolean delete (int id) {
boolean f = false;
String sql = "delete from course where id='" + id + "'"; Connection conn = DBUtil.getConn();
Statement state = null;
int a = 0; try {
state = conn.createStatement();
a = state.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(state, conn);
} if (a > 0) {
f = true;
}
return f;
} /**
* 淇敼
* @param name
* @param pass
*/
public boolean update(Course course) {
String sql = "update course set name='" + course.getName() + "', teacher='" + course.getTeacher() + "', classroom='" + course.getClassroom()
+ "' where id='" + course.getId() + "'";
Connection conn = DBUtil.getConn();
Statement state = null;
boolean f = false;
int a = 0; try {
state = conn.createStatement();
a = state.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(state, conn);
} if (a > 0) {
f = true;
}
return f;
} /**
* 楠岃瘉璇剧▼鍚嶇О鏄惁鍞竴
* true --- 涓嶅敮涓�
* @param name
* @return
*/
public boolean name(String name) {
boolean flag = false;
String sql = "select name from course where name = '" + name + "'";
Connection conn = DBUtil.getConn();
Statement state = null;
ResultSet rs = null; try {
state = conn.createStatement();
rs = state.executeQuery(sql);
while (rs.next()) {
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(rs, state, conn);
}
return flag;
} /**
* 閫氳繃ID寰楀埌璇剧▼淇℃伅
* @param id
* @return
*/
public Course getCourseById(int id) {
String sql = "select * from course where id ='" + id + "'";
Connection conn = DBUtil.getConn();
Statement state = null;
ResultSet rs = null;
Course course = null; try {
state = conn.createStatement();
rs = state.executeQuery(sql);
while (rs.next()) {
String name = rs.getString("name");
String teacher = rs.getString("teacher");
String classroom = rs.getString("classroom");
course = new Course(id, name, teacher, classroom);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.close(rs, state, conn);
} return course;
} /**
* 閫氳繃name寰楀埌Course
* @param name
* @return
*/
public Course getCourseByName(String name) {
String sql = "select * from course where name ='" + name + "'";
Connection conn = DBUtil.getConn();
Statement state = null;
ResultSet rs = null;
Course course = null; try {
state = conn.createStatement();
rs = state.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String teacher = rs.getString("teacher");
String classroom = rs.getString("classroom");
course = new Course(id, name, teacher, classroom);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.close(rs, state, conn);
} return course;
} /**
* 鏌ユ壘
* @param name
* @param teacher
* @param classroom
* @return
*/
public List<Course> search(String name, String teacher, String classroom) {
String sql = "select * from course where ";
if (name != "") {
sql += "name like '%" + name + "%'";
}
if (teacher != "") {
sql += "teacher like '%" + teacher + "%'";
}
if (classroom != "") {
sql += "classroom like '%" + classroom + "%'";
}
List<Course> list = new ArrayList<>();
Connection conn = DBUtil.getConn();
Statement state = null;
ResultSet rs = null; try {
state = conn.createStatement();
rs = state.executeQuery(sql);
Course bean = null;
while (rs.next()) {
int id = rs.getInt("id");
String name2 = rs.getString("name");
String teacher2 = rs.getString("teacher");
String classroom2 = rs.getString("classroom");
bean = new Course(id, name2, teacher2, classroom2);
list.add(bean);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(rs, state, conn);
} return list;
} /**
* 鍏ㄩ儴鏁版嵁
* @param name
* @param teacher
* @param classroom
* @return
*/
public List<Course> list() {
String sql = "select * from course";
List<Course> list = new ArrayList<>();
Connection conn = DBUtil.getConn();
Statement state = null;
ResultSet rs = null; try {
state = conn.createStatement();
rs = state.executeQuery(sql);
Course bean = null;
while (rs.next()) {
int id = rs.getInt("id");
String name2 = rs.getString("name");
String teacher2 = rs.getString("teacher");
String classroom2 = rs.getString("classroom");
bean = new Course(id, name2, teacher2, classroom2);
list.add(bean);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(rs, state, conn);
} return list;
} }
package com.hjf.entity;

public class Course {

    private int id;
private String name;
private String teacher;
private String classroom; public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTeacher() {
return teacher;
}
public void setTeacher(String teacher) {
this.teacher = teacher;
}
public String getClassroom() {
return classroom;
}
public void setClassroom(String classroom) {
this.classroom = classroom;
} public Course() {} public Course(int id, String name, String teacher, String classroom) {
this.id = id;
this.name = name;
this.teacher = teacher;
this.classroom = classroom;
} public Course(String name, String teacher, String classroom) {
this.name = name;
this.teacher = teacher;
this.classroom = classroom;
}
}
package com.hjf.service;

import java.util.List;

import com.hjf.dao.CourseDao;
import com.hjf.entity.Course; /**
* CourseService
* 鏈嶅姟灞�
* @author Hu
*
*/
public class CourseService { CourseDao cDao = new CourseDao(); /**
* 娣诲姞
* @param course
* @return
*/
public boolean add(Course course) {
boolean f = false;
if(!cDao.name(course.getName())) {
cDao.add(course);
f = true;
}
return f;
} /**
* 鍒犻櫎
*/
public void del(int id) {
cDao.delete(id);
} /**
* 淇敼
* @return
*/
public void update(Course course) {
cDao.update(course);
} /**
* 閫氳繃ID寰楀埌涓�涓狢ourse
* @return
*/
public Course getCourseById(int id) {
return cDao.getCourseById(id);
} /**
* 閫氳繃Name寰楀埌涓�涓狢ourse
* @return
*/
public Course getCourseByName(String name) {
return cDao.getCourseByName(name);
} /**
* 鏌ユ壘
* @return
*/
public List<Course> search(String name, String teacher, String classroom) {
return cDao.search(name, teacher, classroom);
} /**
* 鍏ㄩ儴鏁版嵁
* @return
*/
public List<Course> list() {
return cDao.list();
}
}
package com.hjf.servlet;

import java.io.IOException;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.hjf.entity.Course;
import com.hjf.service.CourseService; /**
* Servlet implementation class CourseServlet
*/
@WebServlet("/CourseServlet")
public class CourseServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
CourseService service = new CourseService();
/**
* @see HttpServlet#HttpServlet()
*/
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String method = req.getParameter("method"); if ("add".equals(method)) {
add(req, resp);
} else if ("del".equals(method)) {
del(req, resp);
} else if ("update".equals(method)) {
update(req, resp);
} else if ("search".equals(method)) {
search(req, resp);
} else if ("getcoursebyid".equals(method)) {
getCourseById(req, resp);
} else if ("getcoursebyname".equals(method)) {
getCourseByName(req, resp);
} else if ("list".equals(method)) {
list(req, resp);
}
} /**
* 添加
* @param req
* @param resp
* @throws IOException
* @throws ServletException
*/
private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
req.setCharacterEncoding("utf-8");
//获取数据
String name = req.getParameter("name");
String teacher = req.getParameter("teacher");
String classroom = req.getParameter("classroom");
Course course = new Course(name, teacher, classroom); //添加后消息显示
if(service.add(course)) {
req.setAttribute("message", "添加成功");
req.getRequestDispatcher("add.jsp").forward(req,resp);
} else {
req.setAttribute("message", "课程名称重复,请重新录入");
req.getRequestDispatcher("add.jsp").forward(req,resp);
}
} /**
* 全部
* @param req
* @param resp
* @throws ServletException
*/
private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
req.setCharacterEncoding("utf-8"); List<Course> courses = service.list();
req.setAttribute("courses", courses);
req.getRequestDispatcher("list.jsp").forward(req,resp);
} /**
* 通过ID得到Course
* @param req
* @param resp
* @throws ServletException
*/
private void getCourseById(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
req.setCharacterEncoding("utf-8");
int id = Integer.parseInt(req.getParameter("id"));
Course course = service.getCourseById(id);
req.setAttribute("course", course);
req.getRequestDispatcher("detail2.jsp").forward(req,resp);
} /**
* 通过名字查找
* 跳转至删除
* @param req
* @param resp
* @throws IOException
* @throws ServletException
*/
private void getCourseByName(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
req.setCharacterEncoding("utf-8");
String name = req.getParameter("name");
Course course = service.getCourseByName(name);
if(course == null) {
req.setAttribute("message", "查无此课程!");
req.getRequestDispatcher("del.jsp").forward(req,resp);
} else {
req.setAttribute("course", course);
req.getRequestDispatcher("detail.jsp").forward(req,resp);
}
} /**
* 删除
* @param req
* @param resp
* @throws IOException
* @throws ServletException
*/
private void del(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
req.setCharacterEncoding("utf-8");
int id = Integer.parseInt(req.getParameter("id"));
service.del(id);
req.setAttribute("message", "删除成功!");
req.getRequestDispatcher("del.jsp").forward(req,resp);
} /**
* 修改
* @param req
* @param resp
* @throws IOException
* @throws ServletException
*/
private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
req.setCharacterEncoding("utf-8");
int id = Integer.parseInt(req.getParameter("id"));
String name = req.getParameter("name");
String teacher = req.getParameter("teacher");
String classroom = req.getParameter("classroom");
Course course = new Course(id, name, teacher, classroom); service.update(course);
req.setAttribute("message", "修改成功");
req.getRequestDispatcher("CourseServlet?method=list").forward(req,resp);
} /**
* 查找
* @param req
* @param resp
* @throws ServletException
*/
private void search(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
req.setCharacterEncoding("utf-8");
String name = req.getParameter("name");
String teacher = req.getParameter("teacher");
String classroom = req.getParameter("classroom");
List<Course> courses = service.search(name, teacher, classroom);
req.setAttribute("courses", courses);
req.getRequestDispatcher("searchlist.jsp").forward(req,resp);
}
}
package com.hjf.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; /**
* 鏁版嵁搴撹繛鎺ュ伐鍏�
* @author Hu
*
*/
public class DBUtil { public static String db_url = "jdbc:mysql://localhost:3306/course?useUnicode=true&characterEncoding=utf8";
public static String db_user = "root";
public static String db_pass = "123456"; public static Connection getConn () {
Connection conn = null; try {
Class.forName("com.mysql.jdbc.Driver");//鍔犺浇椹卞姩
conn = DriverManager.getConnection(db_url, db_user, db_pass);
} catch (Exception e) {
e.printStackTrace();
} return conn;
} /**
* 鍏抽棴杩炴帴
* @param state
* @param conn
*/
public static void close (Statement state, Connection conn) {
if (state != null) {
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
} if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} public static void close (ResultSet rs, Statement state, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
} if (state != null) {
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
} if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} public static void main(String[] args) throws SQLException {
Connection conn = getConn();
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql ="select * from course";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
if(rs.next()){
System.out.println("绌�");
}else{
System.out.println("涓嶇┖");
}
}
}

Java实现数据库与eclipse的连接的更多相关文章

  1. JAVA与数据库MySQL相连接

    JDBC(Java数据库连接体系结构): 是Java实现数据库访问的应用程序编程接口,主要功能是管理存放在数据库中的数据.通过接口对象,应用程序可以完成与数据库的连接,执行SQL语句,从数据库中获取结 ...

  2. Java连接Oracle数据库的三种连接方式

    背景: 这两天在学习Oracle数据库,这里就总结下自己上课所学的知识,同时记录下来,方便整理当天所学下的知识,也同时方便日后自己查询. SQL语句的话,这里我就不多讲了,感觉和其他的数据库(MySQ ...

  3. Java操作数据库——使用连接池连接数据库

    Java操作数据库——使用连接池连接数据库 摘要:本文主要学习了如何使用JDBC连接池连接数据库. 传统方式和连接池方式 传统方式的步骤 使用传统方式在Java中使用JDBC连接数据库,完成一次数据库 ...

  4. JAVA:当数据库重启后连接池没有自动识别的解决办法

    今天发现服务器上的一个服务程序出现问题,软件抛出:Connection reset by peer: socket write error 无法正常提供服务,找了一下原因,原来是因为数据库服务器重启, ...

  5. 在Eclipse中连接SQL

    原创 在Eclipse中连接SQL分为如下几个步骤: 1.加载驱动程序 2.创建连接对象 3.创建执行SQL语句的对象 4.执行SQL语句 5.关闭new出来的对象 1.加载驱动程序(以SQL为例) ...

  6. Eclipse中连接Sql Sever2008 -----转自Yogurshine

    Eclipse中连接Sql Sever2008 -----转自Yogurshine 一 SQl Sever服务器配置 1我之前已经安装好SQL Sever 2008R2.(注意:安装一遍未成功时,一定 ...

  7. Java操作数据库——使用JDBC连接数据库

    Java操作数据库——使用JDBC连接数据库 摘要:本文主要学习了如何使用JDBC连接数据库. 背景 数据持久化 数据持久化就是把数据保存到可掉电式存储设备中以供之后使用.大多数情况下,特别是企业级应 ...

  8. 使用Java纯代码实现MySQL的连接

      建立数据库 1. 点击连接-->MySQL: 输入连接名 . 主机名/IP地址 .端口 .用户名.密码(没有密码就省略),然后点击确定,建立的表格是灰色表示关闭状态,双击开启 2. 重新创建 ...

  9. mySql事务_ _Java中怎样实现批量删除操作(Java对数据库进行事务处理)?

      本文是记录Java中实现批量删除操作(Java对数据库进行事务处理),在开始之前先来看下面这样的一个页面图: 上面这张图片显示的是从数据库中查询出的出租信息,信息中进行了分页处理,然后每行的前面提 ...

随机推荐

  1. 模块_pip、os模块

    一个python文件就是一个模块 1.标准模块 python自带的模块就是标准模块,也就是可以直接import进来的就是标准模块 import json import random import da ...

  2. MySQL插入去重命令_REPLACE INTO

    以主键和unique索引为依据. INSERT INTO:表中不存在对应的记录,则插入:若存在对应的记录,则报错: INSERT IGNORE INTO:表中不存在对应的记录,则插入:若存在对应的记录 ...

  3. Docker Kubernetes 创建管理 Pod

    Docker Kubernetes 容器扩容与缩容 环境: 系统:Centos 7.4 x64 Docker版本:18.09.0 Kubernetes版本:v1.8 管理节点:192.168.1.79 ...

  4. ★Pandas 零碎知识

    1 修改属性 1.1 修改1列的类型属性: df['总金额'] = pd.to_numeric(df['总金额']) #转变dataframe的1列为数值型 1.2 多列设为数值型:(使用DataFr ...

  5. ant_<target>标签含义与使用

    <target>标记目标 目标是一个或多个任务的集合,任务是一段可执行的代码:构建文件中包含一个项目,在项目内部声明了所有目标: <target name = "run&q ...

  6. 【论文笔记】Dynamic Routing Between Capsules

    Dynamic Routing Between Capsules 2018-09-16 20:18:30 Paper:https://arxiv.org/pdf/1710.09829.pdf%20 P ...

  7. 【Visual Studio 扩展工具】如何在ComponentOneFlexGrid树中显示RadioButton

    概述 在ComponentOne Enterprise .NET控件集中,FlexGrid表格控件是用户使用频率最高的控件之一.它是一个功能强大的数据管理工具,轻盈且灵动,以分层的形式展示数据(数据呈 ...

  8. angular --- s3core移动端项目(三)

    angular.module('myApp') .directive('listActive',functon(){ return { restrict:'A', scope:{ listActive ...

  9. Promise使用

    Promise可以进行异步操作,比起回调函数,更加容易维护. 首先创建一个简单的Promise var p = new Promise( () => {}); console.log(p); / ...

  10. 【文献08】多移动机器人轨迹跟踪控制系统设计与实现-运动学ADRC控制

    参考: 陈俊, 俞立, 滕游. 多移动机器人轨迹跟踪控制系统设计与实现[J]. 计算机测量与控制, 2017(7). https://drive.wps.cn/view/p/28819052019?f ...