不能将 null 设置为唯一列

cannot set null to a unique column

所以这是我的 table

CREATE TABLE "client" (
"id"    INTEGER,
"name"  TEXT COLLATE NOCASE,
"surname"   TEXT COLLATE NOCASE,
"number"    TEXT UNIQUE COLLATE NOCASE,
"car_brand" TEXT,
"modele"    TEXT,
"phone_nbr" TEXT,
PRIMARY KEY("id" AUTOINCREMENT));

当我从我的 java 应用程序添加新语句时,我只能将一次 NULL 添加到列号,但我可以从数据库浏览器添加许多空值 这是我使用的代码

String number = tf_number.getText();
      if(tf_number.getText().trim().isEmpty())
          number = null;
    String name = tf_name.getText();
    String surname = tf_surname.getText();
    String phoneNbr = tf_phoneNbr.getText();
    String car_brand = tf_brand.getText();
    String modele = tf_modele.getText();
    Client c = new Client(name, surname, number, car_brand, modele, phoneNbr);
    ClientCRUD pcd = new ClientCRUD();
    pcd.addClient(p);

这是 sql 错误

[SQLITE_CONSTRAINT_UNIQUE] A UNIQUE constraint failed (UNIQUE constraint failed: client.number)

这是 addClient() 函数

public void addClient(Client t) {
try {
        
    String requete = "INSERT INTO CLIENT(name,surname,number,car_brand,MODELE,phone_nbr)"
    + "VALUES ('"+t.getClientName()+"','"+t.getClientSurname()+"','"+t.getNumber()+"',"
            + "'"+t.getCarBrand()+"','"+t.getModele()+"','"+t.getPhone()+"')";
    Statement st = MyConnection.getInstance().getCnx()
                .createStatement();

        st.executeUpdate(requete);
        System.out.println("Client added");
        
    } catch (SQLException ex) {
        System.out.println(ex.getMessage());
    }
    }

有什么解决办法吗?

您的代码插入了字符串“null”,而不是像您的浏览器那样插入真正的 null。 因此在该唯一列中只能有 1 个值为“null”的字符串。

您可以使用带参数的 preparedStatement 而不是您使用的语句。 例如:

PreparedStatement preparedStatement = connection.prepareStatement(sql))

这回答了如何使用准备语句插入 null:Insert null using prepared statement

您的 sql 查询字符串应该有参数。 查看有关准备好的语句的更多信息:Prepared Statements Tutorial

 public void save(Person person) {
    String query = "INSERT INTO person_info (" +
            " name_p, " +
            " age, " +
            " address, " +
            " email " +
            ")" +
            "VALUES(?, ?, ?, ?)";

    try(Connection connection = dbConnection.getConnection()) {
        PreparedStatement prepStatement = connection.prepareStatement(query);

        prepStatement.setString(1, person.getName());
        prepStatement.setInt(2, person.getAge());
        prepStatement.setString(3, person.getAddress());
        prepStatement.setString(4, null);

        prepStatement.execute();
    }
    catch (SQLException e){
        e.printStackTrace();
    }
}

##这将解决您的问题