Good day!
In order to access the mysql server, I used the JConnect and my code is as follows:
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();
}
To put the data in the database, I used the following code:
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);
}
}
But there's an error on row 1. COLUMN COUNT DOESN'T MATCH THE VALUE AT ROW What does it mean? Please advise. Thank you.
If the field is auto-increment, you should not assign anything to it, remove it from your SQL prepared statement string and just set everything else, the auto increment will do the job by itself.
PreparedStatement stmt = connect.prepareStatement("INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...) ");
get rid of first column to have:
PreparedStatement stmt = connect.prepareStatement("INSERT INTO table_name (column2, column3,...) VALUES ( value2, value3,...) ");
and replace values with question marks and set them as you do later on.
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();
NOTICE: decremented indices (the number of the question mark value).
Hope that helps!