使用Jconnect的Java

时间:2011-02-24 06:52:19

标签: java jconnect

美好的一天!

为了访问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行出现错误。列数与行数不匹配这是什么意思? 请指教。谢谢。

1 个答案:

答案 0 :(得分: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();

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

希望有所帮助!