在C#中使用DataContext和System.Data.SQLite创建数据库

时间:2012-02-27 18:56:48

标签: c# linq system.data.sqlite

我正在编写有关机器硬件的简单应用程序收集信息。我计划在sqlite中存储数据。得到以下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.IO;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;

namespace SQLiteTest
{
    public class MyDB : DataContext
    {
        public Table<Computer> kompy;
        public MyDB(string connection) : base(connection) { }
        public MyDB(IDbConnection connection) : base(connection) { }
    }


    [Table]
    public class Computer
    {
        [Column(IsPrimaryKey = true, CanBeNull = false)]
        public uint CompId;

        [Column]
        public uint CompanyId;

        [Column]
        public string CompName;
    }


    class Program
    {
        static void Main(string[] args)
        {
            string rootPath = Environment.CurrentDirectory;
            string dbPath = rootPath + "\\db.sqlite3";

            SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();
            builder.Add("Data Source", dbPath);

            SQLiteConnection sqlcnn = new SQLiteConnection(builder.ConnectionString);
            MyDB db = new MyDB(sqlcnn);
            db.CreateDatabase();
            db.SubmitChanges();
            db.Dispose();            
        }
    }
}

运行此程序会产生异常:

Unhandled Exception: System.Data.SQLite.SQLiteException: SQLite error
near "DATABASE": syntax error
   at System.Data.SQLite.SQLite3.Prepare(SQLiteConnection cnn, String strSql, SQ
LiteStatement previous, UInt32 timeoutMS, String& strRemain)
   at System.Data.SQLite.SQLiteCommand.BuildNextCommand()
   at System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index)
   at System.Data.SQLite.SQLiteDataReader.NextResult()
   at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavi
or behave)
   at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()
   at System.Data.Linq.SqlClient.SqlProvider.ExecuteCommand(String command)
   at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider
.CreateDatabase()
   at System.Data.Linq.DataContext.CreateDatabase()
   at SQLiteTest.Program.Main(String[] args) in C:\Users\bootch\documents\visual
 studio 2010\Projects\SQLiteTest\SQLiteTest\Program.cs:line 47

1)为什么这段代码不起作用,我缺少什么?

2)有没有办法获得底层sql命令的文本版本以查看错误

3)如果数据库不存在,我想创建数据库和所有表。我很懒,所以我想我可以使用我为运行查询而创建的类型。是否可以使用System.Data.SQLite?

提前致谢,感谢您的评论和解答!

2 个答案:

答案 0 :(得分:3)

看起来您尝试将Linq2Sql与Sqlite一起使用,默认情况下不支持(仅支持SQL Server和SQL Server CE),有关详细信息,请参阅this question

请看一下使用支持Sqlite的Entity Framework

答案 1 :(得分:0)

我刚刚经历了这个并尝试实施。得到相同的错误,然后发现我们可以使用SQLiteConnection创建数据库,如下所示:

sqlcnn.CreateFile("MyDatabase.sqlite");

然后使用&#34; db&#34;你可以做所有的数据库操作。试试吧。