您的位置:首页 > 数据库 > MySQL

JDBC连接mysql

2015-12-07 23:18 561 查看
1.properties 配置文件

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")));


即可用线程池来获取连接。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: