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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章