我使用此代码,在第一次工作但之后,我有一个错误(java.sql.sqlexception重复条目' 1'用于密钥' primary')和(a) )代表主键(自动增量),请帮助。
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);
}
答案 0 :(得分:0)
如果a是自动增量,那么您不需要在sql查询中插入它。
答案 1 :(得分:0)
无需在自动递增字段中插入值。使用
INSERT INTO Bill (field2, field3, field4, field5) VALUES (...);
目前的风格非常不安全。使用PreparedStatement
可以防止SQL注入攻击。请参阅此文章,了解如何:
https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java