JDBC:Mysql數據庫連接基礎工具類

//初始化數據庫連接對象
public static Connection initConnection(){
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = java.sql.DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return conn;
}

//執行SQL語句方法,添加,修改,刪除。
public static boolean execSQL(String sql){
Connection conn = null;
Statement stmt = null;
boolean flag =false;
try {
conn = initConnection();
stmt= conn.createStatement();
flag = stmt.execute(sql);
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}

//執行SQL查詢語句方法,返回結果集對象
public static ResultSet querySQL(String sql){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = initConnection();
stmt= conn.createStatement();
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章