我在我的java应用程序中使用SQLite,我在我的数据库中创建了一些表。
当我将元素插入人员表(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME CHAR(50) NOT NULL UNIQUE)
时,
我在下面得到了例外:
java.sql.SQLException: [SQLITE_CONSTRAINT] Abort due to constraint violation (column NAME is not unique)
at org.sqlite.DB.newSQLException(DB.java:383)
at org.sqlite.DB.newSQLException(DB.java:387)
at org.sqlite.DB.execute(DB.java:342)
at org.sqlite.DB.executeUpdate(DB.java:363)
at org.sqlite.PrepStmt.executeUpdate(PrepStmt.java:85)
at epfl.lca1.spism.DesktopClient$1.run(Myclass.java:71)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:705)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:675)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
我的代码是:
final PreparedStatement s;
Connection db = openOrCreateDatabase();
try {
s = db.prepareStatement("INSERT INTO People"+
"(Name) VALUES"+
"(?)");
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
System.out.printf("A: %d\n", Thread.currentThread().getId());
for (People p : Peoplearray) {
try {
s.setString(1,p.toString());
s.executeUpdate(); // line 71
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
也许有些元素插入两次,我怎么能忽略插入已存在的元素?
答案 0 :(得分:2)
SQLite的INSERT可以与冲突解决子句一起使用,以指定在发生约束违规时会发生什么。 这将忽略任何插入重复值的尝试:
INSERT OR IGNORE INTO People (Name) VALUES (?)
答案 1 :(得分:1)
由于您的Name
列为unique
,因此两个条目/行的名称值不能相同。因此,将您的查询更改为
INSERT INTO People(Name)
Select ? from dual
WHERE NOT EXISTS
(SELECT *
FROM People
WHERE Name= ?)
仅当不存在具有相同名称的条目时,才会插入条目。
只是为了清除混淆DUAL
是大多数数据库中的特殊表。您可以阅读其Wiki。