C# 尝试使用System.Data.SQLite从数据库读取时发生XAML解析异常
表的架构:C# 尝试使用System.Data.SQLite从数据库读取时发生XAML解析异常,c#,sqlite,C#,Sqlite,表的架构: CREATE TABLE songOrder(songid int, pos int, stanza int, foreign key(songid) references songs(id)); CREATE VIRTUAL TABLE stanzas using fts3(pos int, lyrics text, songid int); CREATE TABLE songs(id integer primary key, name text); 导致崩溃的代码:
CREATE TABLE songOrder(songid int, pos int, stanza int, foreign key(songid)
references songs(id));
CREATE VIRTUAL TABLE stanzas using fts3(pos int, lyrics text, songid int);
CREATE TABLE songs(id integer primary key, name text);
导致崩溃的代码:
InitilizeComponent();
using (SQLiteConnection db = new
SQLiteConnection("DataSource=test.db;Version=3"))
{
db.Open();
String sql = "select name from songs";
using (SQLiteCommand cmd = new SQLiteCommand(sql, db))
using (SQLiteDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//This is the line causing the crash
//Program runs just fine when this line does not execute
Debug.WriteLine(reader["id"]);
songs.Add(new song() {Name = (string)reader["name"]});
}
}
db.Close();
}
lbSongs.ItemsSource = songs;
在Visual Studio中向我显示的异常:
A first chance exception of type 'System.Windows.Markup.XamlParseException'
occurred in PresentationFramework.dll
Additional information: 'The invocation of the constructor on type
's3IO_Test.MainWindow'
that matches the specified binding constraints threw an exception.'
Line number '3' line position '9'.
如果我查看输出,我会看到:
中发生了类型为“System.IndexOutOfRangeException”的首次意外异常
System.Data.SQLite.dll
如果我从一个空数据库开始(这意味着while循环首先不会执行),那么代码的其余部分就可以工作了,因此我不知道为什么尝试读取主键会导致xmlparseexception,这两者似乎与我无关
我编写调试程序是因为我认为在song类中添加一个“int-id”变量会导致崩溃 您的select语句
String sql = "select name from songs";
仅从songs
表返回列name
如果您更改为:
String sql = "select id, name from songs";
行Debug.WriteLine(reader[“id”])代码>应能正常工作
错误是由于试图使用给定的列名访问SQLiteDataReader
中不存在的列
在@HighCore的评论方面,您可以对代码进行一些改进,但这些改进超出了这个问题的范围。我不确定您的意思是什么?