gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:25:53 25 4
gpt4 key购买 nike

我正在编写简单的应用程序来收集有关机器硬件的信息。我计划将数据存储在 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 可以吗?

提前感谢评论和回答!

最佳答案

看起来您正在尝试将 Linq2Sql 与默认不支持的 Sqlite 一起使用(仅支持 SQL Server 和 SQL Server CE),请参阅 this question更多细节。

看看使用 Entity Framework ,它支持 Sqlite。

关于c# - 在 C# 中使用 DataContext 和 System.Data.SQLite 创建数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9470583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com