首先导入要连接的数据库的包(如:mysql 导入commons-collections-3.1.jar)
private static Properties ps = new Properties();
static {
try {
InputStream in = JdbcUtils.class.getClassLoader()
.getResourceAsStream("config\\config.properties");
ps.load(in);
// 注册驱动
Class.forName(ps.getProperty("driverclassname"));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
//数据连接配置放在properties文件中 driverclassname=com.mysql.jdbc.Driver url=jdbc:mysql:///manager
//username=root password=root
return DriverManager.getConnection(ps.getProperty("url"), ps
.getProperty("username"), ps.getProperty("password"));
}
public static void closeRS(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void closeConn(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void closeStmt(Statement stmt) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}