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对数据库进行事务处理),在开始之前先来看下面这样的一个页面图: 上面这张图片显示的是从数据库中查询出的出租信息,信息中进行了分页处理,然后每行的前面提 ...
随机推荐
- springMVC学习路线3-整合spring(annotion方式)
个人认为使用框架并不是很难,关键要理解其思想,这对于我们提高编程水平很有帮助.不过,如果用都不会,谈思想就变成纸上谈兵了!!!先技术,再思想.实践出真知. 1.基本概念 1.1 Spring Sp ...
- sublime package control INSTALLATION
Simple The simplest method of installation is through the Sublime Text console. The console is acces ...
- jQuery 查找元素2
jQuery 查找元素2 :first <ul> <li>list item 1</li> <li>list item 2</li> < ...
- adb shell 命令之----pm
常用的用法: 查看已经安装的包: pm list packages 查看已经安装的包以及apk路径(-3:只看第三方应用: -s:只看系统应用) -f: see their associated fi ...
- DDD之BoundedContext
原文 BoundedContext Bounded Context is a central pattern in Domain-Driven Design. It is the focus of D ...
- PHP钩子的简单介绍
<?php /** * 钩子类 */ class Hook { static public function execute($type, $model='') { if($model == ' ...
- 微信小程序之 真机键盘弹窗遮盖input框
正常效果: 问题效果: 发现这个问题后呢,我先去看了api,api上是这么说的 哦吼~ 然后我也不知道是不是我的打开方式不对还是什么~~ 没有效果~~ 那怎么办呢~~ 换方法呗~~ 我只好用这个方 ...
- Maven 的 settings.xml 配置中的mirror节点
maven2的setting.xml大家都知道,里面有个mirrors节点,用来配置镜像URL. mirrors可以配置多个mirror,每个mirror有id,name,url,mirrorOf属性 ...
- QT编程环境
(1)QT的工具 ① assistant 帮助手册 ② qmake -v 查看qt版本 ③ qmake -project 可以把项目的源文件组织成项目的描述文件 .pro ④ qmake 可以根据.p ...
- leecode第一百四十八题(排序链表)
class Solution { public: void sort_list(ListNode* head1, ListNode* head2,int len)//在原链表上进行排序 { ListN ...