1.预编译
创建数据库day0528和表t_user
CREATE DATABASE day0528; USE day0528; CREATE TABLE t_user( id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(40), PASSWORD VARCHAR(40), email VARCHAR(40), birthday DATE ); INSERT INTO t_user(NAME,PASSWORD,email,birthday) VALUES('小龙女','16','[email protected]','2001-1-1'); INSERT INTO t_user(NAME,PASSWORD,email,birthday) VALUES('姬如雪','17','[email protected]','2002-2-2'); INSERT INTO t_user(NAME,PASSWORD,email,birthday) VALUES('女帝','18','[email protected]','2003-3-3'); SELECT * FROM t_user;
User.java
package zh.jdbc.demo; import java.util.Date; public class User { private Integer id; private String name; private String password; private String email; private Date birthday;// java.util.Date public User() { } public User(Integer id, String name, String password, String email, Date birthday) { super(); this.id = id; this.name = name; this.password = password; this.email = email; this.birthday = birthday; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } 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; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", password=" + password + ", email=" + email + ", birthday=" + birthday + "]"; } }
JDBCUtils.java
package zh.jdbc.demo; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCUtils { private JDBCUtils() { } // 获取数据库连接 public static Connection getConnection(String driverClassName, String url, String username, String password) { try { Class.forName(driverClassName); } catch (ClassNotFoundException e) { e.printStackTrace(); } Connection connection = null; try { connection = DriverManager.getConnection(url, username, password); return connection; } catch (SQLException cause) { throw new RuntimeException("获取数据库连接失败", cause); } } // 关闭资源 public static void close(Statement statement, Connection connection) { if (statement != null) { try { statement.close(); } catch (SQLException cause) { throw new RuntimeException("关闭Statement失败", cause); } statement = null; } if (connection != null) { try { connection.close(); } catch (SQLException cause) { throw new RuntimeException("关闭数据库连接失败", cause); } } connection = null; } // 关闭资源 public static void close(ResultSet resultSet, Statement statement, Connection connection) { if (resultSet != null) { try { resultSet.close(); } catch (SQLException cause) { throw new RuntimeException("关闭ResultSet失败", cause); } } resultSet = null; close(statement, connection); } }
UserDao.java
package zh.jdbc.demo; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Date; import java.util.List; public class UserDao { public UserDao() { } private String driverClassName = "com.mysql.jdbc.Driver"; private String url = "jdbc:mysql://localhost:3306/day0528"; private String username = "root"; private String password = "zh1277718668"; // 增加 public boolean insert(User user) { Connection connection = null; PreparedStatement pstatement = null; try { connection = JDBCUtils.getConnection(driverClassName, url, username, password); String updateSQL = "insert into t_user(name,password,email,birthday) values(?,?,?,?)"; pstatement = connection.prepareStatement(updateSQL); pstatement.setString(1, user.getName()); pstatement.setString(2, user.getPassword()); pstatement.setString(3, user.getEmail()); Date birthday = user.getBirthday();// // java.util.Date pstatement.setDate(4, new java.sql.Date(birthday.getTime())); int insertNum = pstatement.executeUpdate(); if (insertNum > 0) { return true; } else { return false; } } catch (Exception cause) { throw new RuntimeException("插入数据失败", cause); } finally { JDBCUtils.close(pstatement, connection); } } // 删除 public boolean delete(int id) { Connection connection = null; PreparedStatement pstatement = null; try { connection = JDBCUtils.getConnection(driverClassName, url, username, password); String deleteSQL = "delete from t_user where id = ?"; pstatement = connection.prepareStatement(deleteSQL); pstatement.setInt(1, id); int deleteNum = pstatement.executeUpdate(); if (deleteNum > 0) { return true; } else { return false; } } catch (Exception cause) { throw new RuntimeException("删除数据失败", cause); } finally { JDBCUtils.close(pstatement, connection); } } // 修改 public boolean update(User user) { Connection connection = null; PreparedStatement pstatement = null; try { connection = JDBCUtils.getConnection(driverClassName, url, username, password); String updateSQL = "update t_user set name =?,password=?,email=?,birthday=? where id=?"; pstatement = connection.prepareStatement(updateSQL); pstatement.setString(1, user.getName()); pstatement.setString(2, user.getPassword()); pstatement.setString(3, user.getEmail()); pstatement.setDate(4, new java.sql.Date(user.getBirthday() .getTime())); pstatement.setInt(5, user.getId()); int updateNum = pstatement.executeUpdate(); if (updateNum > 0) { return true; } else { return false; } } catch (Exception cause) { throw new RuntimeException("修改数据失败", cause); } finally { JDBCUtils.close(pstatement, connection); } } // 根据id查询 public User load(int id) { User user = null; Connection connection = null; PreparedStatement pstatement = null; ResultSet resultSet = null; try { connection = JDBCUtils.getConnection(driverClassName, url, username, password); String querySQL = "select * from t_user where id = ?"; pstatement = connection.prepareStatement(querySQL); pstatement.setInt(1, id); resultSet = pstatement.executeQuery(); user = new User(); resultSet.next();// 光标默认在第一行之前,因此这里要下移一行 user.setId(resultSet.getInt("id")); user.setName(resultSet.getString("name")); user.setPassword(resultSet.getString("password")); user.setEmail(resultSet.getString("email")); // java.util.Date 是 java.sql.Date 的父类 user.setBirthday(resultSet.getDate("birthday")); return user; } catch (Exception cause) { throw new RuntimeException("查询失败", cause); } finally { JDBCUtils.close(resultSet, pstatement, connection); } } // 查询所有 public List<User> findAll() { List<User> userList = null; Connection connection = null; PreparedStatement pstatement = null; ResultSet resultSet = null; try { userList = new ArrayList<User>(); connection = JDBCUtils.getConnection(driverClassName, url, username, password); String querySQL = "select * from t_user"; pstatement = connection.prepareCall(querySQL); resultSet = pstatement.executeQuery(); while (resultSet.next()) { User user = new User(); user.setId(resultSet.getInt("id")); user.setName(resultSet.getString("name")); user.setPassword(resultSet.getString("password")); user.setEmail(resultSet.getString("email")); // java.util.Date 是 java.sql.Date 的父类 user.setBirthday(resultSet.getDate("birthday")); userList.add(user); } return userList; } catch (Exception cause) { throw new RuntimeException("查询失败", cause); } finally { JDBCUtils.close(resultSet, pstatement, connection); } } }UserDao.java
package zh.jdbc.demo; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.junit.Test; public class UserDaoDemo { @Test public void insert() { /** * 添加user */ UserDao userDao = new UserDao(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date birthday = null; try { birthday = dateFormat.parse("2004-4-4"); } catch (ParseException e) { e.printStackTrace(); } User user = new User(5, "李逍遥", "19", "[email protected]", birthday); boolean insert = userDao.insert(user); System.out.println(insert); } @Test public void delete() { /** * 根据id删除user */ UserDao userDao = new UserDao(); boolean delete = userDao.delete(4); System.out.println(delete); } @Test public void update() { /** * 修改user */ UserDao userDao = new UserDao(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date birthday = null; try { birthday = dateFormat.parse("2001-11-11"); } catch (ParseException e) { e.printStackTrace(); } User user = new User(1, "神仙姐姐", "18", "[email protected]", birthday); boolean update = userDao.update(user); System.out.println(update); } @Test public void load() { /** * 根据id查询user */ UserDao userDao = new UserDao(); for (int i = 1; i <= 3; i++) { User user = userDao.load(i); System.out.println(user); } // User [id=1, name=神仙姐姐, password=18, [email protected], birthday=2001-11-11] // User [id=2, name=姬如雪, password=17, [email protected], birthday=2002-02-02] // User [id=3, name=女帝, password=18, [email protected], birthday=2003-03-03] } @Test public void findAll() { /** * 查询所有user */ UserDao userDao = new UserDao(); List<User> userList = userDao.findAll(); System.out.println(userList); // [User [id=1, name=神仙姐姐, password=18, [email protected], birthday=2001-11-11], // User [id=2, name=姬如雪, password=17, [email protected], birthday=2002-02-02], // User [id=3, name=女帝, password=18, [email protected], birthday=2003-03-03]] } }
insert结果:
delete结果:
update结果:
2.批处理
(1)Statement批处理
package zh.jdbc.demo; import java.sql.Connection; import java.sql.Statement; import java.util.Arrays; /** * Statement批处理 * * @author ZH * */ public class BatchDemo1 { public static void main(String[] args) { String driverClassName = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/day0528"; String username = "root"; String password = "zh1277718668"; Connection connection = null; Statement statement = null; try { connection = JDBCUtils.getConnection(driverClassName, url, username, password); statement = connection.createStatement(); String sql1 = "insert into t_user(name,password,email,birthday) values('赵灵儿','19','[email protected]','2004-4-4')"; String sql2 = "insert into t_user(name,password,email,birthday) values('龙葵','20','[email protected]','2005-5-5')"; String sql3 = "insert into t_user(name,password,email,birthday) values('小仙女','21','[email protected]','2006-6-6')"; statement.addBatch(sql1); statement.addBatch(sql2); statement.addBatch(sql3); int[] nums = statement.executeBatch(); System.out.println(Arrays.toString(nums));//[1, 1, 1] } catch (Exception cause) { throw new RuntimeException("插入数据失败", cause); } finally { JDBCUtils.close(statement, connection); } } }
结果:
(2)PreparedStatement批处理
package zh.jdbc.demo; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.Arrays; /** * PreparedStatement批处理 * * @author ZH * */ public class BatchDemo2 { public static void main(String[] args) { String driverClassName = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/day0528"; String username = "root"; String password = "zh1277718668"; Connection connection = null; PreparedStatement pstatement = null; try { connection = JDBCUtils.getConnection(driverClassName, url, username, password); String deleteSQL = "delete from t_user where id= ?"; pstatement = connection.prepareStatement(deleteSQL); for (int id = 3; id <= 5; id++) { pstatement.setInt(1, id); pstatement.addBatch(); } int[] nums = pstatement.executeBatch(); System.out.println(Arrays.toString(nums));//[1, 1, 1] } catch (Exception cause) { throw new RuntimeException("删除数据失败", cause); } finally { JDBCUtils.close(pstatement, connection); } } }
结果:
3.大数据处理
(1)CLOB数据处理:文本数据
CREATE TABLE t_clob( id INT PRIMARY KEY AUTO_INCREMENT, readme TEXT ); SELECT * FROM t_clob;
【存数据】
package zh.jdbc.demo; import java.io.BufferedReader; import java.io.FileReader; import java.io.Reader; import java.sql.Connection; import java.sql.PreparedStatement; /** * 存CLOB数据:文本数据 * * @author ZH * */ public class CLOBDemo1 { public static void main(String[] args) { String driverClassName = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/day0528"; String username = "root"; String password = "zh1277718668"; Connection connection = null; PreparedStatement pstatement = null; try { connection = JDBCUtils.getConnection(driverClassName, url, username, password); String insertSQl = "insert into t_clob(readme) values(?)"; pstatement = connection.prepareStatement(insertSQl); Reader reader = new BufferedReader(new FileReader( "F:/day0528//a.txt")); pstatement.setClob(1, reader); int num = pstatement.executeUpdate(); System.out.println(num); } catch (Exception cause) { throw new RuntimeException("插入数据失败", cause); } finally { JDBCUtils.close(pstatement, connection); } } }
结果:
【取数据】
package zh.jdbc.demo; import java.io.BufferedReader; import java.io.Reader; import java.sql.Clob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; /** * 取CLOB数据:文本数据 * * @author ZH * */ public class CLOBDemo2 { public static void main(String[] args) { String driverClassName = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/day0528"; String username = "root"; String password = "zh1277718668"; Connection connection = null; PreparedStatement pstatement = null; ResultSet resultSet = null; try { connection = JDBCUtils.getConnection(driverClassName, url, username, password); String querySQl = "select * from t_clob where id = ?"; pstatement = connection.prepareStatement(querySQl); pstatement.setInt(1, 1); resultSet = pstatement.executeQuery(); resultSet.next(); Clob clob = resultSet.getClob("readme"); Reader reader = clob.getCharacterStream(); BufferedReader bReader = new BufferedReader(reader); String line = null; while ((line = bReader.readLine()) != null) { System.out.println(line); } // 静夜思 // 李白 // 床前明月光, // 疑是地上霜。 // 举头望明月, // 低头思故乡。 } catch (Exception cause) { throw new RuntimeException("插入数据失败", cause); } finally { JDBCUtils.close(pstatement, connection); } } }
(2)BLOB数据处理:二进制数据
CREATE TABLE t_blob( id INT PRIMARY KEY AUTO_INCREMENT, picture BLOB ); SELECT * FROM t_blob;
【存数据】
package zh.jdbc.demo; import java.io.FileInputStream; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; /** * 存BLOB数据:二进制数据 * * @author ZH * */ public class BLOBDemo1 { public static void main(String[] args) { String driverClassName = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/day0528"; String username = "root"; String password = "zh1277718668"; Connection connection = null; PreparedStatement pstatement = null; try { connection = JDBCUtils.getConnection(driverClassName, url, username, password); String insertSQl = "insert into t_blob(picture) values(?)"; pstatement = connection.prepareStatement(insertSQl); InputStream inputStream = new FileInputStream( "F://day0528//lyf.jpg"); pstatement.setBlob(1, inputStream); int num = pstatement.executeUpdate(); System.out.println(num);//1 } catch (Exception cause) { throw new RuntimeException("插入数据失败", cause); } finally { JDBCUtils.close(pstatement, connection); } } }
结果:
【取数据】
package zh.jdbc.demo; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; /** * 取BLOB数据:二进制数据 * * @author ZH * */ public class BLOBDemo2 { public static void main(String[] args) { String driverClassName = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/day0528"; String username = "root"; String password = "zh1277718668"; Connection connection = null; PreparedStatement pstatement = null; ResultSet resultSet = null; try { connection = JDBCUtils.getConnection(driverClassName, url, username, password); String querySQl = "select * from t_blob where id = ?"; pstatement = connection.prepareStatement(querySQl); pstatement.setInt(1, 1); resultSet = pstatement.executeQuery(); resultSet.next(); Blob blob = resultSet.getBlob("picture"); InputStream in = blob.getBinaryStream(); OutputStream out = new FileOutputStream("F://day0528//神仙姐姐.jpg"); byte[] buff = new byte[1024]; int len = 0; while ((len = in.read(buff)) != -1) { out.write(buff, 0, len); } out.flush(); out.close(); in.close(); } catch (Exception cause) { throw new RuntimeException("插入数据失败", cause); } finally { JDBCUtils.close(pstatement, connection); } } }
结果: