dbcp
1.引入jar包

匯入這兩個jar包
下載jar包地址:Maven Repository: Search/Browse/Explore (mvnrepository.com)
(進去網站后直接在搜索框搜索并下載即可)
2.配置后綴為 .properties 檔案
如例:
1 #<!-- 連接設定 --> 2 driverClassName=com.mysql.cj.jdbc.Driver 3 url=jdbc:mysql://localhost:3306/test02 4 username=root 5 password=root 6 7 #<!-- 初始化連接 --> 8 initialSize=10 9 10 #<!-- 最大連接數量 --> 11 maxActive=50 12 13 #<!-- 最大空閑連接 --> 14 maxIdle=20 15 16 #<!-- 最小空閑連接 --> 17 minIdle=5 18 19 #<!-- 超時等待時間(單位毫秒) --> 20 maxWait=50000 21 22 #<!-- 編碼方式 --> 23 connectionProperties=useUnicode=true;characterEncoding=utf8 24 25 ##<!-- 指定由連接池所創建的連接自動提交 --> 26 defaultAutoCommit=true 27 28 #<!-- 指定由連接池所創建的連接的事務級別 --> 29 defaultTransactionIsolation=REPEATABLE_READ
3.創建utils包(獲取connection,釋放連接資源)
1 public class JdbcUtils_c3p0 { 2 3 private static DataSource dataSource; 4 static { 5 try { 6 7 //創建資料源 工廠模式 --》創建 8 dataSource = new ComboPooledDataSource(); 9 10 11 } catch (Exception e) { 12 e.printStackTrace(); 13 } 14 } 15 16 //獲取連接 17 public static Connection getConnection() throws Exception{ 18 return dataSource.getConnection(); 19 20 } 21 //釋放鏈接資源 22 public static void release(Connection connection, Statement statement, ResultSet resultSet){ 23 try { 24 if (resultSet != null) { 25 resultSet.close(); 26 } 27 if (statement != null) { 28 statement.close(); 29 } 30 if (connection != null) { 31 connection.close(); 32 } 33 }catch (Exception e){ 34 e.printStackTrace(); 35 } 36 } 37 }
4.測驗
(我這里是以添加一條資料為例)
1 Connection connection = null; 2 PreparedStatement ps = null; 3 ResultSet resultSet =null; 4 //1.獲取資料庫連接 5 try { 6 connection = JdbcUtils_c3p0.getConnection(); 7 String sql = "insert into student (name,sex,birthday,tall) values (?,?,?,?)"; 8 ps = connection.prepareStatement(sql); //預編譯sql 先寫sql,然后不執行 9 //手動為引數賦值 10 ps.setString(1, "嗷嗷嗷"); 11 ps.setString(2, "男"); 12 ps.setString(3, "2002.1.8"); 13 ps.setDouble(4, 1.75); 14 //執行 15 ps.executeUpdate(); 16 17 } catch (Exception e) { 18 e.printStackTrace(); 19 } finally { 20 JdbcUtils.release(connection, ps, resultSet); 21 } 22 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/413157.html
標籤:MySQL
上一篇:mac下進入mysql,提示command not found的解決方法(親測有效)
下一篇:排序規則
