Search code examples
mysqlsqljdbcadditionrecords

How to add a record to a MySQL Database from JDBC


Im having an issue trying to add a record to a MySQL Database. My database has 5 columns (id,names,players,points,position) and i have declared the id as "Auto-Increment " and "primary". Then, when i am trying to add a record, i get the error Column count doesn't match value count at row 1. This happens when my code has this statement,not asking input form a user becuase the id is supposed to auto-increment itself from the database.

String sql1 = "INSERT INTO teams VALUES (?,?,?,?)";

I was told that I shouldn't add another ? to the VALUES() because i dont need to auto-increment it again.

This is my code :

try
  {    
   conn_pr1 = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=12345");
   conn1 = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=12345");
   stmt1 = conn1.createStatement();
   rs1 = stmt1.executeQuery("SELECT * FROM teams");
   String sql1 = "INSERT INTO teams VALUES (?,?,?,?)";
   ps1 =conn_pr1.prepareStatement(sql1);
   String str1 = JOptionPane.showInputDialog(null,"Team name : ");
   String str2 = JOptionPane.showInputDialog(null,"Players : ");
   String str3 = JOptionPane.showInputDialog(null,"Points : ");
   String str4 = JOptionPane.showInputDialog(null,"Position : ");
   int int2 = Integer.parseInt(str2);
   int int3 = Integer.parseInt(str3);
   int int4 = Integer.parseInt(str4);
   ps1.setString(1,str1);
   ps1.setLong(2,int2);
   ps1.setLong(3,int3);
   ps1.setLong(4,int4);
   ps1.executeUpdate();
   System.out.println("\n Successfully added " + str1 + " to database test1!");
                            System.out.println("\n After Changes : ");

                                              System.out.println("___________________________________________________________________________________");
  while (rs1.next())
      {
        System.out.println(" Id : " + rs1.getString(1) + " | Team : " + rs1.getString(2) + " | Players : " + rs1.getString(3) + " | Points : " + rs1.getString(4) + " | Position : " + rs1.getString(5));
      }
        conn1.close();
        conn_pr1.close();
        stmt1.close();
        ps1.close();
        rs1.close();
   } catch ( SQLException se)
        {
        se.printStackTrace();
        }
}
                });

Solution

  • INSERT INTO teams (names,players,points,position) VALUES (?,?,?,?) should do the trick.