JDBC连接mysql
2015-12-07 23:18
561 查看
1.properties 配置文件
2.建一个用来获取连接的类
3.threadlocal的使用
其类似于map,key-value组合,key为线程,value为connection
4.线程池的使用
定义线程池private static BasicDataSource ds;
后续在静态块中设置如下参数
即可用线程池来获取连接。
driver=com.mysql.jdbc.Driver #url url=jdbc:mysql://localhost:3306/pabitel #user user=root #password password=493656696
2.建一个用来获取连接的类
public class DBHelper { private DBHelper(){} private static String url; private static String driver; private static String user; private static String pwd; private static ThreadLocal<Connection> tl=new ThreadLocal<Connection>(); static{ try { Properties prop=new Properties(); InputStream is=DBHelper.class.getClassLoader().getResourceAsStream("properties.properties"); prop.load(is); driver=prop.getProperty("driver"); user=prop.getProperty("user"); pwd=prop.getProperty("password"); url=prop.getProperty("url"); Class.forName(driver); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } public static Connection getConnection() throws SQLException{ Connection conn=DriverManager.getConnection(url,user,pwd); tl.set(conn); return conn; } public static void closeConnection(){ Connection conn=tl.get(); if(conn!=null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } tl.remove(); } } }
3.threadlocal的使用
其类似于map,key-value组合,key为线程,value为connection
4.线程池的使用
定义线程池private static BasicDataSource ds;
后续在静态块中设置如下参数
ds=new BasicDataSource(); ds.setDriverClassName(prop.getProperty("driver")); ds.setUrl(prop.getProperty("url")); ds.setUsername(prop.getProperty("user")); ds.setPassword(prop.getProperty("psw")); ds.setInitialSize(Integer.parseInt(prop.getProperty("initsize"))); ds.setMaxActive(Integer.parseInt(prop.getProperty("maxactive"))); ds.setMaxWait(Integer.parseInt(prop.getProperty("maxwait"))); ds.setMinIdle(Integer.parseInt(prop.getProperty("minidle"))); ds.setMaxIdle(Integer.parseInt(prop.getProperty("maxidle")));
即可用线程池来获取连接。
相关文章推荐
- MySQL如何执行关联查询
- MySQL索引之主键索引
- 关于mysql的存储过程的学习与总结
- MySQL索引之聚集索引介绍
- MySQL主从配置
- MySQL中innoDB表设计优化
- MySQL的启动流程及启动时常见错误分析
- MySQL忘记root密码后如何找回?
- Ubuntu下MySQL初始化的正确姿势
- mysql中数据中文乱码问题
- MySQL分区表的管理~2
- mysql (create temporary table table_name )临时表创建
- mysql远程访问
- MySQL数据类型和常用字段属性总结
- MySql数据库之-------java编程所需要的知识(基础)
- MAC下安装MySql遇到的问题
- mysql一条语句update多条记录
- mysql
- Mysql Explain 详解
- Mysql学习笔记八,Mysql优化篇,常用sql技巧和常见问题