未处理的SQLite异常

时间:2017-02-08 19:00:11

标签: c# sqlite unhandled-exception

我正在关注一个youtube视频,该视频创建了一个基本的C#控制台应用程序,它将创建并写入SQLite数据库。视频中的代码执行但我收到一个未处理的异常,指出{" SQL逻辑错误或缺少数据库\ r \ ntable Mytable没有名为Name&#34的列;}

以下是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;

namespace SQLiteProject
{
    class Program
    {
        static void Main(string[] args)
        {
            string createQuery = @"CREATE TABLE IF NOT EXISTS
                                    [Mytable] (
                                    [Id} INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
                                    [Name] NVARCHAR(2048) NULL,
                                    [Gender] NVARCHAR(2048) NULL)";
            System.Data.SQLite.SQLiteConnection.CreateFile("sample.db3");
            using(System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("data source=sample.db3"))
            {
                    using(System.Data.SQLite.SQLiteCommand cmd=new System.Data.SQLite.SQLiteCommand(conn))
                    {
                        conn.Open();
                        cmd.CommandText = createQuery;
                        cmd.ExecuteNonQuery();
                        cmd.CommandText = "INSERT INTO Mytable(Name,Gender) values('Brett','male')";
                        cmd.ExecuteNonQuery();

                        cmd.CommandText = "SELECT * from Mytable";
                        using(System.Data.SQLite.SQLiteDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                Console.WriteLine(reader["Name"]+ ":" + "reader['Gender']");
                            }
                            conn.Close();
                        }

                     }
                }
            Console.ReadLine();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

CREATE TABLE区域中的错误导致括号和花括号出现问题。部分应为:

string createQuery = @"CREATE TABLE IF NOT EXISTS
                                    [Mytable] (
                                    [Id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
                                    [Name] NVARCHAR(2048) NULL,
                                    [Gender] NVARCHAR(2048) NULL)";