如何实现删除数据库信息后,反馈结果呢

jiugui 2016-08-16 03:48:46
程序按照提示输入准考证信息后,删除对应的数据,并返回结果;如果成功删除的,返回“”删除成功“”;如果输入的准考证号不存在的,提示“查无此人”。现在我是能做到删除数据,但不知道怎么样反馈结果,难道要先用准考证号在数据库中查询一遍有没有对应的数据,在做删除操作吗?真要这样是不是效率太低了点吧? 以下是我的程序:
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();
}
}
}
...全文
82 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
HerveyHall 2016-08-16
  • 打赏
  • 举报
回复
public static void update(String sql)方法的返回值改成boolean类型的,
statement.executeUpdate(sql);
这句改成
return statement.executeUpdate(sql)>0?true:false;
反馈信息的话根据返回值判断就行了

if(JDBCTools.update(sql))
 System.out.println("删除成功");
else
 System.err.println("查无此人");
ps:第3步和第4步合并

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧