尝试使用System.Data.SQLite从数据库读取时出现XAML Parse异常

时间:2014-07-31 01:10:02

标签: 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);

导致崩溃的代码:

        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,这两个似乎和我无关。

我正在写Debug,因为我原以为在歌曲类中添加一个“int id”变量会导致崩溃。

1 个答案:

答案 0 :(得分:0)

您的选择陈述

String sql = "select name from songs";

只会从name表格返回列songs

如果改为:

String sql = "select id, name from songs";

Debug.WriteLine(reader["id"]);应该正常运行。

该错误是由于尝试使用给定的列名访问SQLiteDataReader中不存在的列。

您可以根据@ HighCore的评论对代码进行改进,但这些改进超出了此问题的范围。