gpt4 book ai didi

java - JDBC SQLite 不强制唯一主键约束

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:12:14 25 4
gpt4 key购买 nike

谁能告诉我为什么我的 SQLite JDBC 数据库没有强制执行唯一主键约束?

建表方法为:

public static void TableCars()
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
System.out.println("Opened database successfully");

stmt = c.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS CARS3 " +
"(REGISTRATION TEXT PRIMRY KEY NOT NULL, " +
" PHONE TEXT NOT NULL," +
" MAKE TEXT NOT NULL, " +
" MODEL TEXT, " +
" COLOUR TEXT)";
stmt.executeUpdate(sql);
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Cars3 created successfully");
}

插入方法是:

 public static void InsertCars(String table, String phone, String registration, String make, String model, String colour)
{
Connection c = null;
PreparedStatement pstmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");

String query="INSERT INTO "+table+" (PHONE,REGISTRATION,MAKE, MODEL,COLOUR) VALUES (?,?,?,?,?)";

pstmt = c.prepareStatement(query);

pstmt = c.prepareStatement
("insert into CARS3 values(?,?,?,?,?)");
pstmt.setString(1,registration);
pstmt.setString(2,phone);
pstmt.setString(3, make);
pstmt.setString(4, model);
pstmt.setString(5, colour);
pstmt.executeUpdate();

pstmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Car Records created successfully");
}

而这行不应该被允许,却可以重复执行的代码是:

DbHandler.InsertCars("Cars3", "1","BN51 MZY", "Mini", "C220", "BLACK");

最佳答案

您的创建 SQL 声明 PRIMRY KEY 而不是 PRIMARY KEY .因此,您的表最初是在没有 PRIMARY KEY 约束的情况下创建的,并且由于您添加了“IF NOT EXISTS”条件,因此在之前删除该表之前,新的创建不会唤醒效果。

可以在 column-constraint 图表中找到创建没有PRIMARY KEY 约束的表的原因:

enter image description here

约束定义错误(PRMARY 不是PRIMARY),(红色标注)导致列约束子语法无法触发。

关于java - JDBC SQLite 不强制唯一主键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26174258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com