【问题标题】:Java Update Query does not workJava 更新查询不起作用
【发布时间】:2014-09-16 13:48:19
【问题描述】:

我有数据访问对象工厂类。有两种方法:一种是检索数据,一种是更新表。检索数据的方法正常工作。但是更新方法不起作用。我无法弄清楚问题所在。请帮忙。

这是工厂类:

public class ChequeDAOImpl implements ChequeDAO {

public DBConnect dbConnection;

@Override
public List<Cheque> getCheques() throws SQLException{

    List<Cheque> cheques = new ArrayList<Cheque>();
    Connection connection = dbConnection.getConnection();

    try{
        Statement statement = connection.createStatement();
        ResultSet result = statement.executeQuery("select * from TblProj");


        while(result.next()) {
            Cheque cheque = new Cheque();   
            cheque.setName(result.getString("Name"));
            cheque.setAmount(result.getDouble("Amount"));
            cheque.setDate(result.getDate("Date"));
            cheque.setChqNum(result.getString("CNumber"));
            cheque.setValue(result.getDouble("Value"));

            cheques.add(cheque);                            
        } 
    }catch(Exception exception){
        exception.printStackTrace();
    }finally{
        connection.close();
    }       

    return cheques;
}

@Override
    public void updateFlag(String chNum) throws SQLException{
         DBConnect Connection = null;
        Connection conn = Connection.getConnection();

        try{                                        


            PreparedStatement stmt = (PreparedStatement) conn.prepareStatement("UPDATE TblProj SET flag = ? WHERE CNumber = ? ");
            int i= stmt.executeUpdate();
            stmt.setString(1, "1");
            stmt.setString(2, chNum);
            if(i>0)
            {
                JOptionPane.showMessageDialog(null, "Updated successfully");

            }



        }

        catch(Exception ex){

           JOptionPane.showMessageDialog(null, ex.toString());
        }
        finally{

            conn.close();
        }
    }


public DBConnect getConnection() {
    return dbConnection;
}

public void setConnection(DBConnect connection) {
    this.dbConnection = connection;
}

}

这就是我使用 updateFlag 方法的方式:

dao.updateFlag(gui.chqNo);

【问题讨论】:

    标签: sql-update dao


    【解决方案1】:

    请重写你的prepared statement如下,首先设置prepared statement的参数,然后使用executeUpdate()方法执行。

    PreparedStatement stmt = (PreparedStatement) conn.prepareStatement("UPDATE TblProj SET flag = ? WHERE CNumber = ?");

            stmt.setInt(1, 1);
            stmt.setString(2, chNum);
            int i= stmt.executeUpdate();
    

    【讨论】:

    • 我按照你说的重写了。但它仍然不起作用。它给出了空指针异常。
    • 我试了几次。但我仍然得到同样的空指针异常。
    猜你喜欢
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多