public class DBUtil {
// 连接对象
private Connection conn = null;
// SQL语句处理对象
PreparedStatement ps = null;
// 结果集对象
ResultSet rs = null;
/**
* 连接数据库
*
* @return Connection
*/
public Connection getConnection() {
// 数据库连接基本信息
String Driver = "com.mysql.jdbc.Driver";
String dbName = "laozhao";
String dbUserName = "root";
String dbUserPwd = "";
String url = "jdbc:mysql://localhost:3306/" + dbName
+ "?characterEncoding=utf8";
try {
// 加载驱动
Class.forName(Driver);
// 连接
conn = DriverManager.getConnection(url, dbUserName, dbUserPwd);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
/**
* 关闭数据库
*/
public void closeConnection() {
// 判断连接不为空则关闭
try {
if (this.rs != null) {
this.rs.close(); // 关闭结果集
}
if (this.ps != null) {
this.ps.close(); // 关闭SQL预处理对象
}
if (this.conn != null) {
this.conn.close(); // 关闭连接
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Java中JDBC连接数据库代码
最新推荐文章于 2022-12-15 13:02:02 发布