Jdbc core code 使用手册

 1 import com.alibaba.druid.pool.DruidDataSource;
 2 import com.alibaba.druid.pool.DruidDataSourceFactory;
 3 import com.alibaba.druid.pool.DruidPooledConnection;
 4 import org.slf4j.Logger;
 5 import org.slf4j.LoggerFactory;
 6 
 7 import java.sql.PreparedStatement;
 8 import java.sql.ResultSet;
 9 import java.sql.SQLException;
10 import java.util.Properties;
11 
12 /**
13  * jdbc core api
14  *
15  * @author ysj 2019-10-18
16  */
17 public class JdbcUtils {
18     private static final Logger log = LoggerFactory.getLogger(JdbcUtils.class);
19 
20     private static DruidDataSource dataSource;
21 
22     static {
23         Properties dbProp = loadProperties("db.properties");
24         try {
25             dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(dbProp);
26         } catch (Exception e) {
27             log.error("数据库连接池创建失败");
28             e.printStackTrace();
29         }
30     }
31 
32     /** 常用函数 */
33     public void local() {
34         try {
35             DruidPooledConnection connection = dataSource.getConnection();
36             connection.setAutoCommit(false);
37             PreparedStatement statement = connection.prepareStatement("select ...");
38             // sql中占位符?设置第一个参数值,index start with 1
39             statement.setString(1,"param1");
40 
41             ResultSet resultSet = statement.executeQuery();
42             resultSet.next();
43             // get 结果集中对应列的值
44             resultSet.getString("field");
45             
46             connection.commit();
47             connection.close();
48         } catch (SQLException e) {
49             e.printStackTrace();
50         }
51     }
52 
53     /** 加载数据库配置  这里通过文件流加载数据库连接相关属性,可以有多种方式 */
54     private static Properties loadProperties(String path) {
55         return null; // 此处省略
56     }
57 
58     /** 单例 */
59     public static synchronized JdbcUtils getInstance() {
60         return new JdbcUtils();
61     }
62 }
原文地址:https://www.cnblogs.com/andea/p/11711683.html