【发布时间】:2011-06-28 07:24:10
【问题描述】:
我希望有人能够帮助我解决我的 SQLite 数据库问题。
使用 C# 查询我的 SQLite 数据库时,我收到了 ConstraintException。完整的异常消息是“Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.”我最初使用 access 构建了这个数据库,效果很好,但由于各种原因,我不得不使用 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 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;
}
任何帮助将不胜感激。谢谢。
【问题讨论】:
标签: c# database database-design sqlite