配置文件连接mysql--数据库
其他数据库只是需要修改一下driverClassName和URL就可以了
这里需要一个工具类,来提供与数据库建立连接和关闭连接。我这里使用DBUtile来命名
第一步:新建一个config.properties的文件,如下:
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/hibernate3
username=root
password=123
#设置连接池的最大连接数
maxActive=20
#设置连接池的最小连接数
minIdle=5
#设置最长等待时间
maxWait=5000
第二步:新建一个DBUtil的工具类,代码如下:
public class DBUtil {
public static BasicDataSource bs=null;
static{
Properties prop=new Properties();
try {
prop.load(DBUtil.class.getClassLoader()
.getResourceAsStream("config.properties"));
String DriverClassName=prop.getProperty("driverClassName");
String url=prop.getProperty("url");
String username=prop.getProperty("username");
String password=prop.getProperty("password");
int maxActive=Integer.parseInt(prop.getProperty("maxActive"));
int minIdle=Integer.parseInt(prop.getProperty("minIdle"));
long maxWait=Long.parseLong(prop.getProperty("maxWait"));
bs=new BasicDataSource();
bs.setDriverClassName(DriverClassName);
bs.setUrl(url);
bs.setUsername(username);
bs.setPassword(password);
bs.setMaxActive(maxActive);
bs.setMinIdle(minIdle);
bs.setMaxWait(maxWait);
} catch (Exception e) {
System.out.println("初始化连接池异常");
}
}
//建立连接
public static Connection getConnection() throws SQLException{
return bs.getConnection();
}
//关闭连接
public static void CloseConnection(Connection conn){
try {
if(conn!=null){
conn.close();
}
} catch (Exception e) {
System.out.println("释放连接发生异常!");
}
}
}
第三步:测试工具类
public void testProperties() {Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try {
conn = DBUtil.getConnection();
stmt=conn.createStatement();
String sql="select * from students";
rs=stmt.executeQuery(sql);
while(rs.next()){
String name=rs.getString("STUDENT_NAME");
int id=rs.getInt("STUDENT_ID");
int age=rs.getInt("STUDENT_AGE");
Student student=new Student(id, name, age);
System.out.println(student);
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("数据库连接异常");
}finally{
try {
DBUtil.CloseConnection(conn);
if(stmt!=null){
stmt.close();
}
if(rs!=null){
rs.close();
}
} catch (Exception e2) {
// TODO: handle exception
}
}
}