我创建了一个带有自动增量主键的表:
String sql = "CREATE TABLE COMPANY " + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + " NAME TEXT NOT NULL)"
接下来,我想在我的数据库中添加一条记录。
然而,当我运行程序时,我收到消息:
PRIMARY KEY约束失败(UNIQUE约束失败:COMPANY.ID)。
任何想法如何自动增加记录号?我没有编辑现有记录我添加了记录。为了插入公司价值,我使用了术语" active"在ID字段中。
public class Main {
public static void main(String[] args) {
String nam;
int ag;
Scanner key = new Scanner(System.in);
System.out.println("\nEnter your name : ");
nam = key.next();
System.out.println("\nEnter your age : ");
ag = key.nextInt();
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "INSERT INTO COMPANY VALUES(" + active + " ,
'" + nam + "', " + ag + ")";
stmt.executeUpdate(sql);
c.commit();
ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;"
);
while ( rs.next() ) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println( "ID = " + id );
System.out.println( "NAME = " + name );
System.out.println( "AGE = " + age );
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " +
e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
}
答案 0 :(得分:0)
首先,不要输入id。它由数据库分配。
其次,我很确定您在插入自动增量表时需要明确指定列:
INSERT INTO COMPANY (name, age) VALUES(?, ?)
请注意,您的CREATE TABLE语句与INSERT语句不匹配。
最后,请查看“SQL注入”。使用预准备语句而不是字符串连接