0

再会!

为了访问mysql服务器,我使用了JConnect,我的代码如下:

  public AddBooks() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/catalog";
            conn = DriverManager.getConnection(url,"root","upittc");
            stmt = conn.prepareStatement("INSERT INTO books VALUES(?,?,?,?,?,?,?,?,?,?,)");

        } catch (Exception exc) {
            JOptionPane.showMessageDialog(null, exc.getMessage());
        }
        initComponents();
    }

要将数据放入数据库中,我使用了以下代码:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
      try {
              stmt.setString(1, jTextField0.getText()); 
              stmt.setString(2, jTextField1.getText());
              stmt.setString(3, jTextField2.getText());
              stmt.setString(4, jTextField3.getText());
              stmt.setString(5, jTextField4.getText());
              stmt.setString(6, Jan2.getSelectedItem().toString());
              stmt.setString(7, Jan3.getSelectedItem().toString());
              stmt.setString(8, jTextField5.getText());
              stmt.setString(9, jTextField6.getText());
              stmt.setString(10, jTextField8.getText());
              stmt.executeUpdate();
              JOptionPane.showMessageDialog(null, "Save Successful!");

      } catch (Exception ex) {
              JOptionPane.showMessageDialog(null, ex);
      }
}

但是第 1 行有一个错误。COLUMN COUNT DOESN'T MATCH THE VALUE AT ROW这是什么意思?请指教。谢谢你。

4

1 回答 1

1

如果该字段是自动递增的,则不应为其分配任何内容,将其从 SQL 准备语句字符串中删除并设置其他所有内容,自动递增将自行完成工作。

PreparedStatement stmt = connect.prepareStatement("INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...) ");

摆脱第一列有:

PreparedStatement stmt = connect.prepareStatement("INSERT INTO table_name (column2, column3,...) VALUES ( value2, value3,...) ");

并用问号替换值并像稍后一样设置它们。

          stmt.setString(1, jTextField1.getText());
          stmt.setString(2, jTextField2.getText());
          stmt.setString(3, jTextField3.getText());
          stmt.setString(4, jTextField4.getText());
          stmt.setString(5, Jan2.getSelectedItem().toString());
          stmt.setString(6, Jan3.getSelectedItem().toString());
          stmt.setString(7, jTextField5.getText());
          stmt.setString(8, jTextField6.getText());
          stmt.setString(9, jTextField8.getText());
          stmt.executeUpdate();

注意:递减索引(问号值的数量)。

希望有帮助!

于 2011-02-24T07:00:58.727 回答