1.JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。
本案例介绍java连接数据库的增删改查操作
1.首先我们要有一个数据库表
/*在MySQL中创建一个名称为chapter01的数据库,
然后在该数据库中创建一个users表,SQL语句如下所示*/
CREATE DATABASE jdbc;
USE jdbc;
CREATE TABLE users(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(40),
password VARCHAR(40),
email VARCHAR(60),
birthday DATE
)CHARACTER SET utf8 COLLATE utf8_general_ci;
/*数据库和表创建成功后,再向users表中插入3条数据,SQL语句如下所示*/
INSERT INTO users(NAME,PASSWORD,email,birthday)
VALUES('zs','123456','zs@sina.com','1980-12-04');
INSERT INTO users(NAME,PASSWORD,email,birthday)
VALUES('lisi','123456','lisi@sina.com','1981-12-04');
INSERT INTO users(NAME,PASSWORD,email,birthday)
VALUES('wangwu','123456','wangwu@sina.com','1979-12-04');
/*为了查看数据是否添加成功,使用SELECT语句查询users表,SQL语句如下所示*/
SELECT * FROM users;
创建后表数据如图
2.实现案例前的准备
一定注意不要忘记在web文件夹下的WEB-INF文件夹下建一个lib文件夹(名字一定叫lib)存放相关第三方jar包
#jar包还未导入
(1)建立一个javaBean对象
#还未整理JavaBean的相关知识
src目录下建一个名为Bean的包用来存放JavaBean对象
user(user有四个属性,每个属性都有与之对应的get和set方法)
定义属性后,可以使用Alt+Insert快捷键创立
package Bean1;
import java.util.Date;
public class User {
int id;
String name;
String password;
String email;
Date birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
#三个对象未说明需要整理
(2)创建JDBCUtils工具类(解放代码,每次连接数据库调用工具类的方法就好了)
src目录下建一个名为Utils的包用来存放JDBCUtils工具类
JDBCUtils.java
package Utils;
import java.sql.*;
//导入sql包所有的类,就不用按需类型导入
public class JDBCUtils {
//连接数据库
public static Connection getConnection() throws Exception {
Connection connection = null;
//1.注册数据库的驱动
Class.forName("com.mysql.jdbc.Driver");
//2.通过DriverManager获取数据库连接
//定义一个url接收JDBC操作数据库的连接地址
String url = "jdbc:mysql://localhost:3306/jdbc";
//定义name和password接收数据库的用户名和密码
String username = "root";
String password = "root";
//3.传入参数完成登录
connection = DriverManager.getConnection(url, username, password);
return connection;
//可以理解为一个登陆数据库的动作,DriverManager.getConnection后面的参数就是你的帐号和密码
//返回的connection就是一个数据库连接对象,通过它你就可以对这个数据库做添删改查动作了
}
//4.关闭数据库连接,释放资源(分别释放ResultSet,Statement,,Connection,也可以合并释放)
public static void release(ResultSet set) {
if (set != null) {
try {
set.close();
} catch (SQLException e) {
e.printStackTrace();
}
set = null;
}
}
public static void release(Statement statement) {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
statement = null;
}
}
public static void release(Connection connection) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
connection = null;
}
}
//需要调用两个参数时用到此方法
public static void release(Statement statement,Connection connection) {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
statement = null;
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
connection = null;
}
}
//需要调用三个参数时用到此方法
public static void release(ResultSet set,Statement statement,Connection connection) {
if (set != null) {
try {
set.close();
} catch (SQLException e) {
e.printStackTrace();
}
set = null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
statement = null;
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
connection = null;
}
}
}
#处理数据异常未整理
(3)创建DAO(创建数据库操作类,数据库的增删改查)
src目录下建一个名为Dao的包用来存放数据库操作类,这里我命名为UserDao
UserDao.java
package Dao;
import Bean1.User;
import Utils.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
//创建数据库操作类,数据库的增删改查
public class UserDao {
//添加操作,增加返回值(是否增加成功)
public boolean insert(User user) {
Connection connection = null;
PreparedStatement statement = null;
try {
//获得数据库连接
connection = JDBCUtils.getConnection();
//书写sql语句
String sql = "insert into users(name,password,email,birthday)values(?,?,?,?)";
//获得PreparedStatement对象,将SQL语句作为实参传入方法
statement = connection.prepareStatement(sql);
//填充占位符
statement.setString(1, user.getName());
statement.setString(2, user.getPassword());
statement.setString(3, user.getEmail());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String date = format.format(user.getBirthday());
statement.setString(4, date);
//执行sql语句
int n = statement.executeUpdate();
if (n > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(statement, connection);
}
return false;
}
//删除数据
public boolean Delete(int id){
Connection connection = null;
PreparedStatement statement = null;
ResultSet set = null;
try {
connection = JDBCUtils.getConnection();//连接数据库
String sql = "delete from users where id="+id;//sql语句
statement = connection.prepareStatement(sql);
int n = statement.executeUpdate(sql);//执行sql语句
//处理操作结果
if(n>0){
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(statement, connection);
}
return false;
}
//查询所有数据操作
public List<User> getAll() {
List<User> list = new ArrayList<>();
Connection connection = null;
PreparedStatement statement = null;
ResultSet set = null;
try {
connection = JDBCUtils.getConnection();//连接数据库
String sql = "select * from users";//sql语句
statement = connection.prepareStatement(sql);
set = statement.executeQuery();//执行sql语句
//操作结果集
while (set.next()) {
//获得每条记录各个字段的值
int id = set.getInt("id");
String name = set.getString("name");
String password = set.getString("password");
String email = set.getString("email");
String birthday = set.getString("birthday");
//将各个字段的值封装进bean对象
User user = new User();
user.setId(id);
user.setName(name);
user.setPassword(password);
user.setEmail(password);
user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
list.add(user);
}
return list;//将集合返回给调用者
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(set, statement, connection);
}
return null;//如果发生异常返回null
}
//通过索引id查询单个数据
public User getByID(int id){
Connection connection = null;
PreparedStatement statement = null;
ResultSet set = null;
try {
connection = JDBCUtils.getConnection();//连接数据库
String sql = "select * from users where id="+id;//sql语句
statement = connection.prepareStatement(sql);
set = statement.executeQuery();//执行sql语句
//操作结果集
while (set.next()) {
//获得每条记录各个字段的值
int userid = set.getInt("id");
String name = set.getString("name");
String password = set.getString("password");
String email = set.getString("email");
String birthday = set.getString("birthday");
//将各个字段的值封装进bean对象
User user = new User();
user.setId(userid);
user.setName(name);
user.setPassword(password);
user.setEmail(email);
user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
return user;//将用户返回给调用者
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(set, statement, connection);
}
return null;//如果发生异常返回null
}
//修改数据
public boolean update(User user) {
Connection connection = null;
PreparedStatement statement = null;
try {
//获得数据库连接
connection = JDBCUtils.getConnection();
//书写sql语句
String sql = "UPDATE users SET name=?,password=?,email=?,birthday=? WHERE id=?";
//获得PreparedStatement对象,将SQL语句作为实参传入方法
statement = connection.prepareStatement(sql);
//填充占位符
statement.setString(1, user.getName());
statement.setString(2, user.getPassword());
statement.setString(3, user.getEmail());
statement.setString(4, new SimpleDateFormat("yyyy-MM-dd").format(user.getBirthday()));
//执行sql语句
int n = statement.executeUpdate();
if (n > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(statement, connection);
}
return false;
}
}