Intro
jdbc 是一套连接数据库的规范,由各数据库分别实现。
MySQL:mysql-connector-java (mvnrepository.com)
注册驱动:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| Class.forName("com.mysql.cj.jdbc.Driver");
public class Driver extends NonRegisteringDriver implements java.sql.Driver { public Driver() throws SQLException { }
static { try { DriverManager.registerDriver(new Driver()); } catch (SQLException var1) { throw new RuntimeException("Can't register driver!"); } } }
|
DriverManager
驱动管理,调用静态方法 getConnection 获取数据库连接对象。
1 2 3 4 5 6 7
| String url = "jdbc:mysql://127.0.0.1:3306/test"; String user = "root"; String password = "123456"; Connector con = DriverManager.getConnection(url,user,password);
con.close()
|
PreparedStatement
Statement 使用的字符串拼接的方式执行 SQL 语句,因此有 SQL 注入风险,必须使用 PreparedStatement。
1 2 3 4 5 6 7 8 9 10 11 12 13
| String sql = "SELECT * FROM user WHERE id = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 2);
ResultSet rs = ps.executeQuery();
ps.close();
|
ResultSet
保存查询记录
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| List<User> al = new ArrayList<>(); try(Connection cn = JDBCUtils.getConnection(); PreparedStatement pre = cn.prepareStatement("select * from user"); ResultSet rs = pre.executeQuery();){ while(rs.next()){ int id = rs.getInt("id"); String name = rs.getString("name"); String email = rs.getString("email"); String password = rs.getString("password"); al.add(new User(id, name, email, password)); } }catch(SQLException e){ JDBCUtils.printSQLException(e); }
|
Transactions
Connection 默认获取的连接是自动提交事务。
Druid
德鲁伊是阿里巴巴开发的连接池技术。druid (mvnrepository.com)
1 2 3 4 5 6 7 8 9
| driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true characterEncoding=utf-8 username=root password=123456 initialSize=10 maxActive=50 maxWait=5000 testWhileIdle=true
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| Properties prop = new Properties(); prop.load(new FileInputStream("src\\druid.properties"));
DataSource ds = DruidDataSourceFactory.createDataSource(prop);
Connection cn = ds.getConnection();
cn.close();
|