无法打开SQLite数据库。

5
使用以下代码:
public void InsertPlatypiRequestedRecord(string PlatypusId, string PlatypusName, DateTime invitationSentLocal)
{
    var db = new SQLiteConnection(SQLitePath);
    {
        db.CreateTable<PlatypiRequested>();
        db.RunInTransaction(() =>
            {
                db.Insert(new PlatypiRequested
                              {
                                  PlatypusId = PlatypusId,
                                  PlatypusName = PlatypusName,
                                  InvitationSentLocal = invitationSentLocal
                              });
                db.Dispose();
            });
    }
}

当我尝试运行程序时,出现了这个错误信息:"SQLite.SQLiteException was unhandled by user code HResult=-2146233088 Message=Cannot create commands from unopened database"

但是,尝试添加 "db.Open()" 并不起作用,因为显然没有这样的方法。


你确定吗?这个网站http://www.devart.com/dotconnect/sqlite/docs/Devart.Data.SQLite~Devart.Data.SQLite.SQLiteConnection.html持不同意见。 - PhoenixReborn
我没有使用dotconnect;也许他们有一个Open方法。 - B. Clay Shannon-B. Crow Raven
2个回答

8
你正在过早地释放数据库(在事务内部)。更好的方式是将其包装在“using”语句中,这将处理db连接对象的释放:
private void InsertPlatypiRequestedRecord(string platypusId, string platypusName, DateTime invitationSentLocal)
{
    using (var db = new SQLiteConnection(SQLitePath))
    {
        db.CreateTable<PlatypiRequested>();
        db.RunInTransaction(() =>
        {
            db.Insert(new PlatypiRequested
            {
                PlatypusId = platypusId,
                PlatypusName = platypusName,
                InvitationSentLocal = invitationSentLocal
            });
        });
    }
}

1
string connecString = @"Data Source=D:\SQLite.db;Pooling=true;FailIfMissing=false";       
/*D:\sqlite.db就是sqlite数据库所在的目录,它的名字你可以随便改的*/
SQLiteConnection conn = new SQLiteConnection(connectString); //新建一个连接
conn.Open();  //打开连接
SQLiteCommand cmd = conn.CreateCommand();

cmd.CommandText = "select * from orders";   //数据库中要事先有个orders表

cmd.CommandType = CommandType.Text;
using (SQLiteDataReader reader = cmd.ExecuteReader())
{
   while (reader.Read())
                Console.WriteLine( reader[0].ToString());
}

您可以在此处下载System.Data.SQLite.dll 链接

这里有一篇关于C#连接SQLite的中文文章


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接