简体   繁体   English

SQL Best删除记录方式

[英]SQL Best delete record way

Which one is the best way to delete records from DB? 哪一种是从数据库删除记录的最佳方法?

Using Spring JDBC 3.1.1 使用Spring JDBC 3.1.1

String SQL="DELETE FROM XXX WHERE USERNAME=?";

Query 1: 查询1:

getJdbcTemplate().execute(SQL, new PreparedStatementCallback<Boolean>() {
            @Override
            public Boolean doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
               ps.setString(1, username);
               return ps.execute();
            }
         });

Query 2: 查询2:

int deletedRecordSize = getJdbcTemplate().update(SQL, username);

As DELETE is an data changing operation you should call executeUpdate in your first Query anyway. 由于DELETE是数据更改操作,因此无论如何您应该在第一个查询中调用executeUpdate This would then return int as well reducing the difference to length and readability of code. 然后,这将返回int并减少代码长度和可读性的差异。

In which case Query 2 looks shorter & cleaner. 在这种情况下, 查询2看起来更短,更干净。

Try this try catch block inside ur deleting method: 试试这个尝试在您的删除方法中捕获块:

try{
                String SQL="DELETE FROM XXX WHERE USERNAME=?";
                ps = conn.prepareStatement(sql); //conn here is the usual object fro DB connection class

                ps.setString(1, username);
                ps.execute();
                JOptionPane.showMessageDialog(null,"DONE DELETING", "DONE",1);
          }catch(SQLException | HeadlessException e){

       }

I think both are the same according to the link 我认为两者根据链接是相同的

http://www.javatpoint.com/spring-JdbcTemplate-tutorial http://www.javatpoint.com/spring-JdbcTemplate-tutorial

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM