手写JDBC - 数据库、驱动信息存储在配置文件
1. 将数据库、驱动信息存储在配置文件
configure.properties
1 url=jdbc:mysql://localhost:3306/数据库名?serverTimezone=GMT&useSSL=false 2 user=用户名,一般是root 3 password=数据库密码 4 driver=com.mysql.cj.jdbc.Driver
2. JDBC工具类
MyDBUtil.java
1 import java.io.InputStream; 2 import java.sql.*; 3 import java.util.Properties; 4 5 /** 6 * 手写实现JDBC工具类 7 * @author Nemo 8 * @version 1.0 9 * @date 2019/4/10 10 */ 11 public class MyDBUtil { 12 private static String url; 13 private static Properties proterties; 14 15 // 注册驱动 16 static { 17 proterties = new Properties; 18 19 InputStream configureStream = MyDBUtil.class.getClassLoader.getResourceAsStream("configure.proterties"); 20 try { 21 properties.load(configureStream); 22 String driver = properties.getProperty("driver"); 23 class.forName(driver); 24 25 url = properties.getProperty("url"); 26 } catch (Exception e) { 27 e.printStackTrace(); 28 } 29 } 30 31 // 获取连接 32 public static Connection getConnection() throw SQLException{ 33 return DriverManager.getConnection(url, properties); 34 } 35 36 // 释放资源 37 public static void release(Statement statement, Connection connection, ResultSet resultSet) { 38 closeQuietly(statement); 39 closeQuietly(connection); 40 closeQuietly(resultSet); 41 } 42 // 重载释放资源 43 public static void release(Statement statement, Connection connection) { 44 closeQuietly(statement); 45 closeQuietly(connection); 46 } 47 48 private static void closeQuietly(AutoCloseable closeable) { 49 if (closeable != null) { 50 try { 51 closeable.close(); 52 } catch (Exception e) { 53 e.printStackTrace(); 54 } 55 } 56 } 57 }
3. 以实现数据库事务为例,演示工具类的使用
TranctionTest.java
1 import org.junit.Test; 2 3 import java.sql.Connection; 4 import java.sql.SQLException; 5 import java.sql.Savepoint; 6 import java.sql.Statement; 7 8 /** 9 * 以数据库事务为例进行演示 10 * @author Nemo 11 * @version 1.0 12 * @date 2019/4/13 13 */ 14 public class TranctionTest { 15 @Test 16 public void traction() throws SQLException { 17 Connection conn = null; 18 Statement stm = null; 19 Savepoint savepoint = null; 20 try { 21 // 获取数据库连接 22 conn = MyDBUtil.getConnection(); 23 24 // 关闭数据库自动commit功能 25 conn.setAutoCommit(false); 26 27 // 建立sql语句 28 stm = conn.cteateStatement(); 29 30 // zs给lisi转账100 31 String sql1 = "update user set money=money-100 where name='zs';"; 32 String sql2 = "update user set money=money+100 where name='lisi';"; 33 34 // wangwu给lisi转账100 35 String sql3 = "update user set money=money-100 where name='wangwu';"; 36 String sql4 = "update user set money=money+100 where name='lisi';"; 37 38 // 提交sql语句 39 stm.executeUpdate(sql1); 40 stm.executeUpdate(sql2); 41 42 // 设置savepoint 43 savepoint = conn.setSavepoint(); 44 45 int i = 1/0; 46 47 stm.executeUpdate(sql3); 48 stm.executeUpdate(sql4); 49 50 conn.commit(); 51 } catch (Exception e) { 52 conn.rollback(savepoint); 53 conn.commit(); 54 } finally { 55 MyDBUtil.release(statement, connection); 56 } 57 } 58 }