我希望有人能够帮助我处理SQLite数据库问题。用C#查询SQlite数据库时出现ConstraintException
我在用C#查询SQLite数据库时收到ConstraintException
。完整的异常消息是“Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
”我最初使用访问工作建立了这个数据库,这很好,但由于各种原因,我不得不使用SQLite重新创建它。
给一点背景 - 这是一个简单的状态调度程序。每个Status
都有一个关联的Account
和Schedule
。我意识到Statuses
和Schedule
是1:1关系,可能在同一个表中,但为了让程序进一步发展,我已将它们分成两个表。
请参阅下面的表格脚本的削减版本(这足以重新创建问题)。
PRAGMA foreign_keys = ON;
CREATE TABLE Accounts
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
Name char(100));
CREATE TABLE Statuses
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
AccountId INTEGER REFERENCES Accounts(ID) ON DELETE CASCADE,
Text char(140));
CREATE TABLE Schedule
(ID INTEGER PRIMARY KEY REFERENCES Statuses(ID) ON DELETE CASCADE,
StartDate char(255),
Frequency INT);
我没有任何问题,直到我创建了两个Statues
并把它们关联到同一Account
。
Accounts
ID Name
1 Fred Blogs
Statuses
ID AccountId Text
1 1 “Some text”
2 1 “Some more text”
Schedule
ID StartDate Frequency
1 16/02/2011 1
2 16/02/2011 1
我使用它抛出异常的select语句是:
SELECT Statuses.Id, Statuses.Text, Accounts.Id, Accounts.Name, Schedule.StartDate, Schedule.Frequency
FROM [Statuses], [Accounts], [Schedule]
WHERE Statuses.AccountId = Accounts.Id AND Statuses.Id = Schedule.Id
如果我运行相同的查询,但删除“Accounts.Id
”列的查询工作正常。
请参阅以下我使用C#代码,但我不认为这是问题
public DataTable Query(string commandText)
{
SQLiteConnection sqliteCon = new SQLiteConnection(ConnectionString);
SQLiteCommand sqliteCom = new SQLiteCommand(commandText, sqliteCon);
DataTable sqliteResult = new DataTable("Query Result");
try
{
sqliteCon.Open();
sqliteResult.Load(sqliteCom.ExecuteReader());
}
catch (Exception)
{
throw;
}
finally
{
sqliteCon.Close();
}
return sqliteResult;
}
任何帮助将不胜感激。谢谢。
感谢您的回复。 Id列很重要,因为我需要将计划链接到状态。每个状态都有相应的时间表。例如,Id 1的状态链接到Id 1的Schedule。Schedule Id是一个外键。此外,我不确定问题是否与Schedule表相关,因为只有在选择[Account.Id]和[Status.Id]时才会出现问题 – 2011-02-16 12:25:19