目录:JDBC技术&CRUD操作&getGeneratedKeys&基于反射实现DBUtils封装&Druid&HikariCP连接池
JDBC技术
入门案例
//1.加载数据库驱动(注册驱动) JDBC4之后无需编写Class.forName(\"com.mysql.jdbc.Driver\");//2.获取连接Connection conn = DriverManager.getConnection(\"jdbc:mysql://127.0.0.1:3306/mydb2\", \"root\", \"123456\");//3.获取执行sql语句命令的对象Statement stat = conn.createStatement();//4.执行sqlboolean f = stat.execute(\"insert into tbuser(username,password) values(\'java-jdbc\',\'112233\')\");//5.处理结果System.out.println(\"执行结果:\"+f);//6.关闭资源stat.close();conn.close();
jdbc中常用的类和接口:
- DriverManager
- Connection
- Statement/PreparedStatement
- ResultSet
DriverManager
驱动管家类,java.sql中提供的一个具体类,内部包含了一些用于加载数据库驱动的方法以及获取连接的操作:
getConnection
使用DriverManager获取数据库连接的三种方式
// 方法一:Connection conn = DriverManager.getConnection(\"jdbc:mysql://127.0.0.1:3306/mydb2\", \"root\", \"123456\");//方法二:// Connection conn = DriverManager.getConnection(\"jdbc:mysql://127.0.0.1:3306/mydb2?user=root&password=123456\");//方法三:// Properties info = new Properties();// info.put(\"user\", \"root\");// info.put(\"password\",\"123456\");// Connection conn = DriverManager.getConnection(\"jdbc:mysql://127.0.0.1:3306/mydb2\", info);
Connection
Connection用于表示从Java程序到数据库的连接通道,通过Connection可以向数据库传输sql命令,并且返回执行结果.另外Connection也可以用于对数据库事务管理,具体使用:
//获取执行sql的命令对象Statement stat = connection.createStatement();//获取sql语句的预处理对象(防止sql注入)PreparedStatement ps = connection.parepareStatement();//获取一个用于发送存储过程调用命令对象CallableStatement pc = connection.prepareCall();//设置禁止事务自动提交connection.setAutoCommit(false);//回滚事务connection.rollback();//事务提交connection.commit();
Statement&PreparedStatement
是一个用于执行sql命令的对象,主要用于执行静态sql(事先准备好的,固定的);由于Statement的固有不安全性(很有可能导致sql注入的风险),因此还提供一个直接子接口:PreparedStatement(预处理命令对象),可以有效的防止sql注入的风险。
Statement中提供的常见方法:
- boolean execute(String sql)
- int executeUpdate(String sql)
- ResultSet executeQuery(String sql)
PreparedStatement提供的方法:
- int executeUpdate();
- ResultSet executeQuery();
//方式SQL注入,使用PreparedStatementpublic static void login2(String username,String password) throws ClassNotFoundException, SQLException {String sql = \"select * from tbuser where username=? and password=?\";//1.加载驱动Class.forName(\"com.mysql.jdbc.Driver\");//2.获取连接Connection conn = DriverManager.getConnection(\"jdbc:mysql:///mydb2\", \"root\", \"123456\");//3.获取预处理sql命令的对象(对传入的sql与进行预编译,防止出现sql注入问题)PreparedStatement ps = conn.prepareStatement(sql);//预处理ps.setString(1, username);ps.setString(2, password);//4.执行ResultSet rs = ps.executeQuery();//5.处理结果if(rs.next()) {System.out.println(\"登录成功!\");}else {System.out.println(\"请检查账号和密码!\");}//6.关闭资源rs.close();ps.close();conn.close();}
Statement和PreparedStatement的区别?
Statement是原始的执行sql命令的对象,不对sql语句做任何处理,可能会因为传入的参数问题导致sql注入,因此存在注入的风险;所以在实际开发中更加推荐使用PreparedStatement,该接口的实现针对sql语句进行了预编译,解决了可能出现的sql注入风险;另外PreparedStatement内部使用预编译机制,从运行效率来看,略高于Statement。
ResultSet
结果集对象,用于表示对于查询语句执行之后的结果,内部的数据可能是一条也可以是多条
CRUD(增删改查)操作
package com.softeem.lesson48.crud;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import com.softeem.lesson48.utils.DBUtils;public class UserCRUD {private Connection conn;/*** 添加数据* @param username* @param password* @return* @throws ClassNotFoundException* @throws SQLException*/public boolean insert(String username,String password) throws ClassNotFoundException, SQLException {PreparedStatement ps = null;try {//DBUtil类参考JDBC基本封装conn = DBUtils.getConn();String sql = \"insert into tbuser(username,password) values(?,?)\";//3.获取sql语句预处理对象ps = conn.prepareStatement(sql);ps.setString(1, username);ps.setString(2, password);//4.执行int i = ps.executeUpdate();//5.处理结果return i > 0;}finally {DBUtils.close(null, ps, conn);}}/*** 修改数据* @param id* @param password* @return* @throws ClassNotFoundException* @throws SQLException*/public boolean update(int id,String password) throws ClassNotFoundException, SQLException {String sql = \"update tbuser set password=? where id=?\";PreparedStatement ps = null;try {conn = DBUtils.getConn();//3.获取sql语句预处理对象ps = conn.prepareStatement(sql);ps.setString(1, password);ps.setInt(2, id);//4.执行int i = ps.executeUpdate();return i > 0;}finally {DBUtils.close(null, ps, conn);}}/*** 删除数据* @param id* @return* @throws ClassNotFoundException* @throws SQLException*/public boolean delete(int id) throws ClassNotFoundException, SQLException {String sql = \"delete from tbuser where id=?\";PreparedStatement ps = null;try {conn = DBUtils.getConn();//3.获取sql语句预处理对象ps = conn.prepareStatement(sql);ps.setInt(1, id);//4.执行int i = ps.executeUpdate();return i > 0;}finally {DBUtils.close(null, ps, conn);}}/*** 查询一条数据* @param username* @return* @throws SQLException*/public Map<String,Object> selectOne(String username) throws SQLException{//声明map作为返回值Map<String,Object> map = new HashMap<String, Object>();String sql = \"select * from tbuser where username=?\";PreparedStatement ps = null;ResultSet rs = null;try {conn = DBUtils.getConn();//3.获取预处理是sql命令的对象ps = conn.prepareStatement(sql);ps.setString(1, username);//4.执行查询rs = ps.executeQuery();if(rs.next()) {//根据列的标签(默认列名,如有设置别名,则标签为别名)获取列值int id = rs.getInt(\"id\");String name = rs.getString(\"username\");String pwd = rs.getString(\"password\");//将获取的数据装入map集合map.put(\"id\", id);map.put(\"username\", name);map.put(\"password\", pwd);}} finally {DBUtils.close(rs, ps, conn);}return map;}/*** 查询所有* @return* @throws SQLException*/public List<Map<String,Object>> selectAll() throws SQLException{List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();String sql = \"select * from tbuser\";PreparedStatement ps = null;ResultSet rs = null;try {conn = DBUtils.getConn();//3.获取预处理是sql命令的对象ps = conn.prepareStatement(sql);//4.执行查询rs = ps.executeQuery();while(rs.next()) {Map<String,Object> map = new HashMap<String, Object>();//根据列的标签(默认列名,如有设置别名,则标签为别名)获取列值int id = rs.getInt(\"id\");String name = rs.getString(\"username\");String pwd = rs.getString(\"password\");//将获取的数据装入map集合map.put(\"id\", id);map.put(\"username\", name);map.put(\"password\", pwd);list.add(map);}} finally {DBUtils.close(rs, ps, conn);}return list;}public static void main(String[] args) throws ClassNotFoundException, SQLException {UserCRUD crud = new UserCRUD();// boolean f = crud.insert(\"softeem123\", \"123softeem\");// boolean f = crud.update(2, \"666666\");// boolean f = crud.delete(12);// System.out.println(\"执行结果:\"+f);// Map<String,Object> map = crud.selectOne(\"softeem\");List<Map<String, Object>> list = crud.selectAll();list.forEach(u->System.out.println(u));}}
getGeneratedKeys获取自动生成键
public class JDBCGenKeys {public static int insert(String eventName) {int id = 0;String sql = \"insert into tblog(event_name) values(?)\";Connection conn = DBUtils.getConn();PreparedStatement ps = null;ResultSet rs = null;try {//获取预处理sql命令的对象,该对象允许返回自动生成的键ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);ps.setString(1, eventName);int i = ps.executeUpdate();if(i > 0) {//返回包含自动生成的键的结果集rs = ps.getGeneratedKeys();id = rs.next() ? rs.getInt(1) : 0;}} catch (SQLException e) {e.printStackTrace();}finally {DBUtils.close(rs, ps, conn);}return id;}public static void main(String[] args) {int id = insert(\"修改数据了\");System.out.println(id);}}
基于反射实现DBUtils封装
详情请见下一个博客QAQ
连接池技术
由于数据库连接是一种资源,这种资源在使用前必须先创建,而这个创建过程是存在时间和空间的开销的,如果每次在执行数据库访问时都创建连接,并且使用完后要关闭连接,这个过程必然是效率低下的;因此,在实际开发中可以考虑在进行数据库操作前,先提前创建并维护一批数据库连接对象,当需要使用时,从这批对象中获取一个连接,用完之后再返还,从而避免了不必要的时间开销,提高程序的运行效率,这种技术在JDBC中称之为连接池技术(Connection Pool)
Druid连接池使用:
使用前先导入Druid的依赖:druid-1.1.9.jar
实现代码:
public class DruidDemo {public static void main(String[] args) throws SQLException {// 创建数据源DruidDataSource dataSource = new DruidDataSource();// dataSource.setDriverClassName(\"com.mysql.jdbc.Driver\");dataSource.setUrl(\"jdbc:mysql://127.0.0.1:3306/mydb2\");dataSource.setUsername(\"root\");dataSource.setPassword(\"123456\");// 设置最大链接数dataSource.setMaxActive(5);// 最小闲置链接数dataSource.setMinIdle(1);// 初始连接个数dataSource.setInitialSize(2);// 设置获取连接的最大等待时间dataSource.setMaxWait(10000);// 获取连接Connection conn1 = dataSource.getConnection();System.out.println(\"conn1:\" + conn1);Connection conn2 = dataSource.getConnection();System.out.println(\"conn2:\" + conn2);Connection conn3 = dataSource.getConnection();System.out.println(\"conn3:\" + conn3);Connection conn4 = dataSource.getConnection();System.out.println(\"conn4:\" + conn4);new Thread() {public void run() {try {sleep(15000);//关闭第四个连接conn4.close();} catch (InterruptedException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}};}.start();Connection conn5 = dataSource.getConnection();System.out.println(\"conn5:\" + conn5);Connection conn6 = dataSource.getConnection();System.out.println(\"conn6:\" + conn6);}}
HikariCP使用
实现代码:
public class HikariCPDemo {public static void main(String[] args) throws SQLException {HikariDataSource ds = new HikariDataSource();ds.setDriverClassName(\"com.mysql.jdbc.Driver\");ds.setJdbcUrl(\"jdbc:mysql://127.0.0.1:3306/mydb2\");ds.setUsername(\"root\");ds.setPassword(\"123456\");//设置最大链接数ds.setMaximumPoolSize(10);//设置最小闲置连接ds.setMinimumIdle(1);//设置最长等链接获取时间ds.setConnectionTimeout(10000);Connection conn = ds.getConnection();System.out.println(conn);}}