Cannot open SQLite database
Asked Answered
S

2

5

Using this code:

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();
            });
    }
}

...I get, "SQLite.SQLiteException was unhandled by user code HResult=-2146233088 Message=Cannot create commands from unopened database"

...but attempting to add a "db.Open()" doesn't work, because there is apparently no such method.

Sycamine answered 20/12, 2012 at 2:36 Comment(2)
Are you sure? This site, devart.com/dotconnect/sqlite/docs/… disagrees.Hemocyte
I'm not using dotconnect; perhaps they do have an Open method.Sycamine
F
8

You are disposing the database prematurely (inside of the transaction). It is better to wrap things up inside of a "using" statement, which will dispose of the db connection:

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
            });
        });
    }
}
Fenderson answered 20/12, 2012 at 3:34 Comment(0)
A
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());
}

you can download System.Data.SQLite.dll here

here is a chinese article for csharp connect sqlite

Allodial answered 20/12, 2012 at 2:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.