Java实现数据库与eclipse的连接
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的连接的更多相关文章
- JAVA与数据库MySQL相连接
JDBC(Java数据库连接体系结构): 是Java实现数据库访问的应用程序编程接口,主要功能是管理存放在数据库中的数据.通过接口对象,应用程序可以完成与数据库的连接,执行SQL语句,从数据库中获取结 ...
- Java连接Oracle数据库的三种连接方式
背景: 这两天在学习Oracle数据库,这里就总结下自己上课所学的知识,同时记录下来,方便整理当天所学下的知识,也同时方便日后自己查询. SQL语句的话,这里我就不多讲了,感觉和其他的数据库(MySQ ...
- Java操作数据库——使用连接池连接数据库
Java操作数据库——使用连接池连接数据库 摘要:本文主要学习了如何使用JDBC连接池连接数据库. 传统方式和连接池方式 传统方式的步骤 使用传统方式在Java中使用JDBC连接数据库,完成一次数据库 ...
- JAVA:当数据库重启后连接池没有自动识别的解决办法
今天发现服务器上的一个服务程序出现问题,软件抛出:Connection reset by peer: socket write error 无法正常提供服务,找了一下原因,原来是因为数据库服务器重启, ...
- 在Eclipse中连接SQL
原创 在Eclipse中连接SQL分为如下几个步骤: 1.加载驱动程序 2.创建连接对象 3.创建执行SQL语句的对象 4.执行SQL语句 5.关闭new出来的对象 1.加载驱动程序(以SQL为例) ...
- Eclipse中连接Sql Sever2008 -----转自Yogurshine
Eclipse中连接Sql Sever2008 -----转自Yogurshine 一 SQl Sever服务器配置 1我之前已经安装好SQL Sever 2008R2.(注意:安装一遍未成功时,一定 ...
- Java操作数据库——使用JDBC连接数据库
Java操作数据库——使用JDBC连接数据库 摘要:本文主要学习了如何使用JDBC连接数据库. 背景 数据持久化 数据持久化就是把数据保存到可掉电式存储设备中以供之后使用.大多数情况下,特别是企业级应 ...
- 使用Java纯代码实现MySQL的连接
建立数据库 1. 点击连接-->MySQL: 输入连接名 . 主机名/IP地址 .端口 .用户名.密码(没有密码就省略),然后点击确定,建立的表格是灰色表示关闭状态,双击开启 2. 重新创建 ...
- mySql事务_ _Java中怎样实现批量删除操作(Java对数据库进行事务处理)?
本文是记录Java中实现批量删除操作(Java对数据库进行事务处理),在开始之前先来看下面这样的一个页面图: 上面这张图片显示的是从数据库中查询出的出租信息,信息中进行了分页处理,然后每行的前面提 ...
随机推荐
- 《CSS世界》读书笔记(五) --height:100%
<!-- <CSS世界> 张鑫旭著 --> 相对简单而单纯的height:auto height:auto比width:auto简单的多,原因在于: CSS默认流是水平方向的, ...
- 使用SVN提交代码,快速简单的换地址方法
1.找到你项目所在的文档,然后删除.svn文件,如下图: 2.然后在使用小乌龟的图标,进行项目的导入,界面如下: 3.然后输入SVN库的地址,点击ok界面如下: 4.同步到eclipse的方法是,复制 ...
- Linux 高级文件管理
1.标准输出(ls -l /dev/stdin 0 ),标准输入(ls -l /dev/stdout 1 ),错误输出(ls -l /dev/stderr 2 ). 2.ls /etc/passwd ...
- centos6安装配置zabbix3被控端
Centos 6.5 Zabbix 3.0.4 zabbix分为zabbix-server(主控端)和zabbix-agent(被控端),本文则介绍安装agent和server端添加监控: 主控端添加 ...
- 【Python62--scrapy爬虫框架】
一.Scrapy Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架,可以应用在包括数据挖掘,信息处理或存储历史数据等一系列的程序中 Scrapy最初是为页面抓取而设计的,也可以应用在 ...
- shadows
http://blog.51cto.com/11975865/2308030 https://www.jianshu.com/p/247cdbabf389 https://baijiahao.baid ...
- react-router 4.0(二)传参
import React from 'react'; import ReactDOM from 'react-dom' import {Link,Route,HashRouter} from 'rea ...
- js parseInt
语法: parseInt(string, radix); string 要被解析的值.如果参数不是一个字符串,则将其转换为字符串(使用 ToString 抽象操作).字符串开头的空白符将会被忽略. ...
- SQL LITE安装
SQLite是一款轻型的嵌入式关系数据库,轻量级,效率高,操作起来也特别方便我们今天来讲解一下SQLite的安装和一些基本操作SQLite下载我是64位机,下载下面的两个解压就好添加path环境变量, ...
- Netflix分享构建Microservices的经验
Netflix分享构建Microservices的经验 http://t.cn/Rwjgutw 新词:Microservices.我觉得就是service oriented architecture的 ...