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連接數據庫代碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.