您的位置:首页 > 数据库

JDBC 连接数据库工具类(properties文件)

2013-06-30 00:16 507 查看
JDBC 连接数据库工具类

Java 类

package com.zhanggaosong.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class MyDBUtil {
private static String driver = null;
private static String url = null;
private static String userName = null;
private static String password = null;
private static ThreadLocal<Connection> tong = new ThreadLocal<Connection>();

static {
try {
Properties p = new Properties();

InputStream inStream = MyDBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");

p.load(inStream);
driver = p.getProperty("driver");
url = p.getProperty("url");
userName = p.getProperty("userName");
password = p.getProperty("password");

} catch (Exception e) {
e.printStackTrace();
}
}

public static Connection getConnetion() {
Connection conn = null;
try {
conn=tong.get();
if(conn==null){
conn=DriverManager.getConnection(url,userName,password);
tong.set(conn);
}
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}

public static void closeConnection(){
Connection conn = tong.get();
if(conn!=null){
try {
conn.close();
tong.set(null);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

jdbc.properties文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/数据库名
userName=root
password=123456
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐