//初始化数据库连接对象
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;
}
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;
}
本文提供了一个使用Java进行数据库操作的简单示例,包括初始化数据库连接、执行SQL语句(如添加、修改、删除记录)及查询数据的方法。示例中详细展示了如何处理可能遇到的异常。
1267

被折叠的 条评论
为什么被折叠?



