您的位置:首页 > 数据库

Java中JDBC连接数据库代码

2017-10-27 14:20 387 查看
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();
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: