JdbcUnit的使用

来源:互联网 发布:mac充电先绿灯后变红 编辑:程序博客网 时间:2024/05/21 21:33
package com.altest.units;


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


public class JdbcUnit {
  
private static Properties properties = null; 
// 只在JdbcUnits被加载时,执行一次
static {     
// 给properties 进行初始化,加载 dbconfig.properties文件到   propertie 中去
try {
InputStream inputStream = JdbcUnit.class.getClassLoader().getResourceAsStream("dbconfig.properties");
       properties = new Properties();

properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}

//加载驱动类
try {
Class.forName(properties.getProperty("driveClassName"));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws  SQLException{
return DriverManager.getConnection(properties.getProperty("url"),properties.getProperty("username"),properties.getProperty("password")); 
}
public static void CloseJdbc(ResultSet resultSet, PreparedStatement preparedStatement,
Connection connection) {
try {
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (preparedStatement != null)
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
0 0