列位置超出范围,ResultSet为'0'

时间:2017-06-08 16:12:28

标签: java sql

一切正常工作都不知道我做了什么,但是当我想在SQL数据库中更新信息时,我一直收到错误。错误:列位置“1”超出范围。此ResultSet的列数为“0”

try
{
     String em = EmailField.getText();
     String na = NameField.getText();
     String su = SurnameField.getText();
     String i = IDField.getText();
     String ce = CellField.getText();

     String query2 = "UPDATE LouwDataBase.Table1Test "
                    + "SET Email = "+"'"+em+"'"+" , "
                    + "Name = "+"'"+na+"'"+" , "
                    + "Surname = "+"'"+su+"'"+" , "
                    + "ID = "+"'"+i+"'"+" , "
                    + "Cell = "+"'"+ce+"'"
                    + " WHERE Email = "+"'"+UserEmailID+"'";

      conn = DriverManager.getConnection("jdbc:derby://localhost:1527/MyDataBase", "LouwDataBase", "1234");
      stat = conn.createStatement();

      try (Connection conn = this.connect();
      PreparedStatement pstmt = conn.prepareStatement(query2)) 
      {
            pstmt.setString(1, em);
            pstmt.setString(3, na);
            pstmt.setString(4, su);
            pstmt.setString(5, i);
            pstmt.setString(6, ce);
            pstmt.executeUpdate();
       } 
       catch (SQLException e) 
       {
            System.out.println(e.getMessage());
       }
} 

1 个答案:

答案 0 :(得分:1)

由于您正在使用PreparedStatement,我认为您需要在查询中包含问号,然后使用pstmt.setString()

try {
  String em = EmailField.getText();
  String na = NameField.getText();
  String su = SurnameField.getText();
  String i = IDField.getText();
  String ce = CellField.getText();

  String query2 = "UPDATE LouwDataBase.Table1Test "
                 + "SET Email = ?, "
                 + "Name = ?, "
                 + "Surname = ?, "
                 + "ID = ?, "
                 + "Cell = ?"
                 + " WHERE Email = ?";

  conn = DriverManager.getConnection("jdbc:derby://localhost:1527/MyDataBase", "LouwDataBase", "1234");
  stat = conn.createStatement();

  try (Connection conn = this.connect();
  PreparedStatement pstmt = conn.prepareStatement(query2)) {
      pstmt.setString(1, em);
      pstmt.setString(3, na);
      pstmt.setString(4, su);
      pstmt.setString(5, i);
      pstmt.setString(6, ce);
      pstmt.executeUpdate();
   } 
   catch (SQLException e) {
      System.out.println(e.getMessage());
   } 
}