黑马程序员技术交流社区
标题:
数据库
[打印本页]
作者:
牛江伟
时间:
2019-8-14 15:56
标题:
数据库
创建数据库工具类:
package cn.itcast.util;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class DBUtil {
static String url;
static String user;
static String password;
//注册驱动
static{
try {
Properties p =new Properties();
p.load(DBUtil.class.getResourceAsStream("jdbc.properties"));
String driver = p.getProperty("driver");
url = p.getProperty("url");
user = p.getProperty("user");
password = p.getProperty("password");
System.out.println(url);
System.out.println(user);
System.out.println(password);
Class.forName(driver);
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection(){
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//关闭资源
public static void close(Statement stmt,Connection conn){
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//关闭资源
public static void close(ResultSet rs,Statement stmt, Connection conn){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2