1.实现第一个JDBC程序
在MySQL中创建一个名称为jdbc的数据库,然后在该数据库中创建一个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;
数据库和表创建成功后,创建插入记录:
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','lisi0sina.com','1981-12-04');
INSERT INTO users (NAME, PASSWORD, email,birthday)
VALUES('wangwu','123456','wangwu@sina.com','1979-12-04');
执行结果如图
?
2.编写JDBC程序
在项目chapter09的src目录下,新建一个名称为chapter02.jdbc.example的包,在该包中创建类Example01,该类用于读取数据库中的users表,并将结果输出到控制台
package chapter12.jdbc.example;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class example01 {
public static void main(String[] args) throws SQLException{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC";
String username = "root";
String password = "123456";
conn = DriverManager.getConnection(url,username,password);
stmt = conn.createStatement();
String sql = "select * from users";
rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String psw = rs.getString("password");
String email = rs.getString("email");
Date birthday = rs.getDate("birthday");
System.out.println(id+" "+name+" "+email+" "+birthday);
}
}catch (ClassNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
}finally {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
rs=null;
}
if (stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
stmt=null;
}
if (conn!=null) {
try {
conn.close();
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
conn=null;
}
}
}
}
结果如图
?
PreparedStatement对象
在该类中使用PreparedStatement对象对数据库进行插入数据的操作
package chapter12.jdbc.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class example02 {
public static void main(String[] args) throws SQLException{
Connection conn = null;
PreparedStatement preStmt = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC";
String username = "root";
String password = "123456";
conn = DriverManager.getConnection(url,username,password);
String sql ="INSERT INTO users (NAME, PASSWORD, email,birthday)"+"VALUES(?,?,?,?)";
preStmt =conn.prepareStatement(sql);
preStmt.setString(1, "zl");
preStmt.setString(2, "123456");
preStmt.setString(3, "zl@sina.com");
preStmt.setString(4, "1789-12-23");
preStmt.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(preStmt!=null) {
try {
preStmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
preStmt = null;
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn=null;
}
}
}
}
查询结果如图
?
ResultSet对象
使用ResultSet对象取出指定数据的信息
?
package chapter12.jdbc.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class example03 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC";
String username = "root";
String password = "123456";
conn = DriverManager.getConnection(url,username,password);
String sql = "select * from users";
stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery(sql);
System.out.print("第2条数据的name值为:");
rs.absolute(2);
System.out.println(rs.getNString("name"));
System.out.print("第1条数据的name值为:");
rs.beforeFirst(); //将指针定位到结果集中第一行数据之前
rs.next(); //指针向后滚动
System.out.println(rs.getString("name"));
System.out.print("第4条数据的name值为:");
rs.afterLast(); //将指针定位到结果集中最后一条数据之后
rs.previous(); //指针向前滚动
System.out.println(rs.getString("name"));
} catch (Exception e) {
e.printStackTrace();
} finally {
if(stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn=null;
}
}
}
}
程序的运行结果如图?
?
使用JDBC完成数据的增删改查
1.创建JavaBean
User类的具体实现方式如下
package chapter12.jdbc.example;
import java.util.Date;
public class user {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
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;
}
private String username;
private String password;
private String email;
private Date birthday;
}
2.创建工具类
由于每次操作数据库时,都需要加载数据库驱动、建立数据库连接以及关闭数据库连接,为了避免代码的重复书写,下面建立一个专门用于数据库相关操作的工具类。在包中创建一个封装了上述操作的工具类JDBCUtils,JDBCUtils的具体实现方式如下
package chapter12.jdbc.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtils {
public static Connection getConnection() throws SQLException,ClassNotFoundException{
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC";
String username = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url,username,password);
return conn;
}
public static void release(Statement stmt, Connection conn) {
if(stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn=null;
}
}
public static void release(ResultSet rs,Statement stmt,Connection conn) {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
release(stmt, conn);
}
}
3.创建DAO
代码如下:
package chapter12.jdbc.example;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import chapter12.jdbc.example.user;
import chapter12.jdbc.example.JDBCUtils;
public class UsersDao {
//添加用户的操作
public boolean insert(user user) {
Connection conn = null;
Statement stmt=null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
stmt = conn.createStatement();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String birthday = sdf.format(user.getBirthday());
String sql = "INSERT INTO users(id,name,password,email,birthday)"+
"VALUES("
+user.getId()
+",'"
+user.getUsername()
+"','"
+user.getPassword()
+"','"
+user.getEmail()
+"','"
+birthday + "')";
System.out.println(sql);
int num = stmt.executeUpdate(sql);
if (num > 0) {
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs,stmt,conn);
}
return false;
}
public ArrayList<user> findAll(){
Connection conn = null;
Statement stmt=null;
ResultSet rs = null;
ArrayList<user> list = new ArrayList<user>();
try {
conn = JDBCUtils.getConnection();
stmt = conn.createStatement();
String sql = "SELECT * FROM users";
rs = stmt.executeQuery(sql);
while(rs.next()) {
user user = new user();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setBirthday(rs.getDate("birthday"));
list.add(user);
}
return list;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs, stmt, conn);
}
return null;
}
public user find(int id) {
Connection conn=null;
Statement stmt=null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
stmt=conn.createStatement();
String sql = "SELECT * FROM users WHERE id=" + id;
rs = stmt.executeQuery(sql);
while(rs.next()) {
user user = new user();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setBirthday(rs.getDate("birthday"));
return user;
}
return null;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs,stmt, conn);
}
return null;
}
public boolean delete(int id) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
stmt= conn.createStatement();
String sql = "DELETE FROM users WHERE id=" + id;
int num =stmt.executeUpdate(sql);
if(num > 0) {
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs, stmt,conn);
}
return false;
}
public boolean update(user user) {
Connection conn =null;
Statement stmt = null;
ResultSet rs = null;
try {
conn= JDBCUtils.getConnection();
stmt = conn.createStatement();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String birthday =sdf.format(user.getBirthday());
String sql = "UPDATE users set name='"+user.getUsername()
+"',password='"+user.getPassword() + "',email='"
+user.getEmail() + "',birthday='" + birthday
+"'WHERE id=" + user.getId();
int num = stmt.executeUpdate(sql);
if (num > 0) {
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtils.release(rs, stmt, conn);
}
return false;
}
}
4.创建测试类
代码如下:
package chapter12.jdbc.example;
import java.util.Date;
import chapter12.jdbc.example.user;
import chapter12.jdbc.example.JDBCUtils;
public class JdbcInsertTest {
public static void main(String[] args) {
//向users表插入一个用户信息
UsersDao ud = new UsersDao();
user user=new user();
user.setId(5);
user.setUsername("hl");
user.setPassword("123");
user.setEmail("hl@sina.com");
user.setBirthday(new Date());
boolean b= ud.insert(user);
System.out.println(b);
}
}
结果如图
?
从查询结果可以看出,users表中添加了一条name为h1的数据,该数据正是文件 JdbclnsertTest.java中所插入的数据。
?编写测试类FindAllUsersTest,该类用于实现读取users表中所有的数据:
package chapter12.jdbc.example;
import java.util.ArrayList;
public class FindAllUsersTest {
public static void main(String[] args) {
UsersDao usersDao = new UsersDao();
ArrayList<user> list = usersDao.findAll();
for (int i=0; i< list.size(); i++) {
System.out.println("第" + (i+1) + "条数据的username的值为:"
+list.get(i).getUsername());
}
}
}
结果如图:
?
编写测试类FindUserByldTest,在该类中实现读取 users表中指定的数据:
package chapter12.jdbc.example;
import chapter12.jdbc.example.UsersDao;
import chapter12.jdbc.example.user;
public class FindUserByldTest {
public static void main(String[] args) {
UsersDao usersDao = new UsersDao();
user user = usersDao.find(1);
System.out.println("id为1的User对象的name值为:"+user.getUsername());
}
}
结果如图:
?
编写测试类UpdateUserTest,在该类中实现修改users表中数据的操作:
package chapter12.jdbc.example;
import java.util.Date;
import chapter12.jdbc.example.UsersDao;
import chapter12.jdbc.example.user;
public class UpdateUserTest {
public static void main(String[] args) {
UsersDao usersDao = new UsersDao();
user user = new user();
user.setId(4);
user.setUsername("zhaoxiaoliu");
user.setPassword("456");
user.setEmail("zhaoxiaoliu@sina.com");
user.setBirthday(new Date());
boolean b=usersDao.update(user);
System.out.println(b);
}
}
查询结果如图:
?
编写测试类DeleteUserTest,该类实现了删除users 表中数据的操作:
package chapter12.jdbc.example;
import chapter12.jdbc.example.UsersDao;
public class DeleteUserTest {
public static void main(String[] args) {
UsersDao usersDao = new UsersDao();
boolean b = usersDao.delete(4);
System.out.println(b);
}
}
?结果如图:
从图中可以看出,users表中id为4的User对象已被成功删除了。至此,使用JDBC对数据库中数据进行增删改查的操作已经完成。
|