连接数据库
先下载jar包 ,或者导入maven
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| public class JDBCTest {
private static final String driver = "com.mysql.cj.jdbc.Driver"; private static final String username = "root"; private static final String password = "root"; private static final String schema = "test"; private static final int port = 3306; private static final String url = "jdbc:mysql://localhost:" + port + "/" + schema+"?serverTimezone=GMT&useUnicode=true&characterEncoding=utf8";
private static Connection conn;
@BeforeClass public static void initJDBC() throws Exception { Class.forName(driver); conn = DriverManager.getConnection(url, username, password); }
@Test public void testRead() { try (Statement s = conn.createStatement(); ResultSet rs = s.executeQuery("SELECT * FROM stu;") ) { ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { for (int i = 1; i <= rsmd.getColumnCount(); i++) { System.out.print(rs.getString(i)+"\t"); } System.out.print("\n"); } } catch (SQLException e) { e.printStackTrace(); } }
@AfterClass public static void destoryJDBC() throws Exception { conn.close(); } }
|
执行SQL语句的Statement
Statement的基本用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| public class JDBCTest { @Test public void testExecuteUpdate(){ try(Statement s = conn.createStatement(); ){ s.executeUpdate("CREATE TABLE stu(" + "sid INT UNSIGNED PRIMARY KEY AUTO_INCREMENT," + "sname VARCHAR(20)," + "age INT ," + "tid INT )"); System.out.println("共有"+0+"条记录受影响"); int records = s.executeUpdate("UPDATE stu SET age=age+1"); System.out.println("共有"+records+"条记录受影响"); } catch (SQLException e) { e.printStackTrace(); } }
@Test public void testExecute(){ try(Statement s = conn.createStatement(); ){ boolean hasResultSet = s.execute("SELECT * FROM stu;"); if(hasResultSet){ try(ResultSet rs = s.getResultSet()){ ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { for (int i = 1; i <= rsmd.getColumnCount(); i++) { System.out.print(rs.getString(i)+"\t"); } System.out.print("\n"); } } }
} catch (SQLException e) { e.printStackTrace(); } } }
|
预编译的PreparedStatement
PreparedStatement
是Statement
的子接口,可以预编译SQL
语句,效率高,还可以防注入。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class JDBCTest { @Test public void testPreparedStatement(){ try(PreparedStatement ps = conn.prepareStatement( "INSERT INTO stu(sname, age) VALUES(?,?) "); ){ for(int i = 0; i < 3; i++){ ps.setString(1,"stu"+i); ps.setInt(2, 20+i); ps.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } } }
|
调用存储过程的CallableStatement
自定义一个加法的存储过程
1 2 3 4 5
| delimiter // create procedure add_num(in a int, in b int, out sum int) begin set sum = a + b; end//
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class JDBCTest { @Test public void testCallableStatement() throws Exception{ try(CallableStatement cs = conn.prepareCall("{CALL add_num(?,?,?)}");){ int a = 5, b = 3; cs.setInt(1, a); cs.setInt(2, b); cs.registerOutParameter(3, Types.INTEGER); cs.execute(); System.out.println(a+"+"+b+"="+cs.getInt(3)); } } }
|
事务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class JDBCTest { @Test public void testTransaction() throws SQLException { conn.setAutoCommit(false); Statement s = conn.createStatement(); s.executeUpdate("INSERT INTO stu(sname) VALUES ('stu1');"); s.executeUpdate("INSERT INTO stu(sname) VALUES ('stu2');"); Savepoint sp = conn.setSavepoint("事务中间点"); s.executeUpdate("INSERT INTO stu(sname) VALUES ('stu3');"); conn.rollback(sp); conn.commit(); } }
|
数据库连接池
DBCP数据源
Tomcat
的连接池使用DBCP
连接池。
在maven中导入
1 2 3 4 5
| <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency>
|
从数据库连接池中获取数据库连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class JDBCTest { @Test public void testDBCP() throws SQLException { BasicDataSource bds = new BasicDataSource(); bds.setDriverClassName(driver); bds.setUrl(url); bds.setUsername(username); bds.setPassword(password); bds.setInitialSize(5); bds.setMaxActive(20); bds.setMinIdle(2); Connection conn = bds.getConnection(); conn.close(); } }
|
C3P0数据源
Hibernate
的连接池使用C3P0
连接池。
在maven中导入
1 2 3 4 5
| <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency>
|
从数据库连接池中获取数据库连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class JDBCTest { @Test public void testC3P0() throws PropertyVetoException, SQLException { ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setDriverClass(driver); cpds.setJdbcUrl(url); cpds.setUser(username); cpds.setPassword(password); cpds.setMaxPoolSize(40); cpds.setMinPoolSize(2); cpds.setInitialPoolSize(10); cpds.setMaxStatements(190); Connection conn = cpds.getConnection(); conn.close(); } }
|