-1

I use this code , in first time it works but after ,I have an error (java.sql.sqlexception duplicate entry '1' for key 'primary')and (a) represent the primary key (auto-increment), please help.

public int a;

String url = "jdbc:mysql://localhost:3306/joebdd";

String driver = "com.mysql.jdbc.Driver";

String user = "root";

String pass = "12345";

try {

    Class.forName(driver).newInstance();

    Connection con = (Connection) DriverManager
            .getConnection(url, user, pass);

    Statement st = (Statement) con.createStatement();

    ResultSet rs1 = (ResultSet) st
            .executeQuery("select count(*) from Bill");

    if (rs1.next()) {
        if (rs1.getInt(1) == 0) {
            a = 0;
        }

        if (rs1.getInt(1) == 1) {
            a = 1;
        }

        else {
            a = rs1.getInt(1);

        }

        st.executeUpdate("insert into Bill  values('"
                + a
                + "','"
                + jTextField2.getText()
                + "','"
                + jLabel7.getText()
                + "','"
                + jTextPane1.getText()
                + "','"
                + Integer.parseInt(jTextField1
                        .getText()) + "')");

    }
}

catch (Exception e) {

    JOptionPane.showMessageDialog(null, e);

}
Guillermo Merino
  • 3,197
  • 2
  • 17
  • 34

2 Answers2

0

If a is autoincrement, then you don't need to insert it in the sql query.

Guillermo Merino
  • 3,197
  • 2
  • 17
  • 34
0
  1. No need to insert a value in the auto-incremented field. Use
    INSERT INTO Bill (field2, field3, field4, field5) VALUES (...);

  2. Current style is very unsafe. Use a PreparedStatement to be safe from SQL Injection attacks. Refer to this article for how:
    https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java

Islay
  • 478
  • 4
  • 17