需要的jar包有 commons-dbutils , commons-dbcp , commons-pool , mysql-connector-java
本地database.propertties 配置为
driverClass=com.mysql.jdbc.Driver url=jdbc:mysql://localhost/mydatabase?useUnicode=true&characterEncoding=GBK username=root password=***
该文件创建在src根目录下
首先做一个DBCP工具类
1 package JDBCDemo; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.util.Properties; 6 7 import javax.activation.DataSource; 8 9 import org.apache.commons.dbcp.BasicDataSource; 10 11 public class DBCPUtils { 12 private DBCPUtils() {}; 13 private static BasicDataSource dbs = new BasicDataSource(); 14 private static String className=""; 15 private static String sqlUrl=""; 16 private static String sqlUser=""; 17 private static String sqlPassword=""; 18 static { 19 initConfig(); 20 //设置基本信息 21 dbs.setDriverClassName(className); 22 dbs.setUrl(sqlUrl); 23 dbs.setUsername(sqlUser); 24 dbs.setPassword(sqlPassword); 25 //对连接池控制数--可不配 26 dbs.setInitialSize(10); //连接池初始化连接数 27 dbs.setMaxActive(8); //最大链接数量 28 dbs.setMaxIdle(5); //最大空闲数 29 dbs.setMinIdle(5); //最小空闲数 30 } 31 public static BasicDataSource getDataSource() { 32 return dbs; 33 } 34 private static void initConfig() { 35 InputStream inf = JDBCUtils.class.getClassLoader().getResourceAsStream("database.propertties"); 36 Properties properties = new Properties(); 37 try { 38 properties.load(inf); 39 className = properties.getProperty("driverClass"); 40 sqlUrl = properties.getProperty("url"); 41 sqlUser = properties.getProperty("username"); 42 sqlPassword = properties.getProperty("password"); 43 } catch (IOException e) { 44 e.printStackTrace(); 45 } 46 } 47 }
应用该工具类 结合 DBUtils 写的demo
1 package JDBCDemo; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.sql.Connection; 6 import java.sql.SQLException; 7 import java.util.Properties; 8 import javax.management.RuntimeErrorException; 9 import org.apache.commons.dbcp.BasicDataSource; 10 import org.apache.commons.dbutils.QueryRunner; 11 12 13 public class DBCPDemo { 14 private static QueryRunner qr = new QueryRunner(DBCPUtils.getDataSource()); 15 public static void main(String[] args) { 16 try { 17 insert(); 18 } catch (Exception e) { 19 e.printStackTrance(); 20 } 21 } 22 public static void insert() throws SQLException { 23 String sql = "insert into zhangwu (name,money) values (?,?)"; 24 Object[] obj = {"麻将支出",100}; 25 int res = qr.update(sql,obj); 26 if (res>0) { 27 System.out.println("插入数据成功"); 28 }else { 29 System.out.println("插入数据失败"); 30 } 31 } 32 }
时间: 2024-10-24 16:07:17