JDBC SQLite不强制使用唯一的主键约束

时间:2014-10-03 06:31:22

标签: java eclipse sqlite jdbc primary-key

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

create table方法是:

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");

1 个答案:

答案 0 :(得分:4)

您的创建SQL指出PRIMRY KEY而不是PRIMARY KEY。因此,您的表最初是在没有PRIMARY KEY约束的情况下创建的,因为您添加了“如果不存在”。条件,新作品赢得了唤醒效果,直到桌子先前被丢弃。

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

enter image description here

约束定义是错误的(PRMARY不是PRIMARY),(如红色所示)使得列约束子语法不被触发。