如何实现删除数据库信息后,反馈结果呢
程序按照提示输入准考证信息后,删除对应的数据,并返回结果;如果成功删除的,返回“”删除成功“”;如果输入的准考证号不存在的,提示“查无此人”。现在我是能做到删除数据,但不知道怎么样反馈结果,难道要先用准考证号在数据库中查询一遍有没有对应的数据,在做删除操作吗?真要这样是不是效率太低了点吧? 以下是我的程序:
public void testDeleteStudent(){
//1.从控制台根据提示输入准考证号
System.out.println("请输入学生的准考证号:");
Scanner scanner =new Scanner(System.in);
//2.生成sql语句
String sql="delete from examstudent where examcard='"+scanner.next()+"'";
//3.执行sql语句
JDBCTools.update(sql);
//4.反馈操作信息
}
下面是JDBCTools的代码:
public class JDBCTools {
// 执行SQL语句 insert,delete,update
public static void update(String sql) {
Connection connection = null;
Statement statement = null;
try {
//建立连接,执行sql语句
connection = JDBCTools.getConnection();
statement = connection.createStatement();
statement.executeUpdate(sql);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 关闭资源
JDBCTools.releaseResult(null, statement, connection);
}
}
// 关闭数据库,释放资源
public static void releaseResult(ResultSet resultSet, Statement statement,
Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}