2016-07-25 95 views
1

我正在尝试使用sqlite + C#开始。我发现SQLite-lib不是标准库,所以我在每个引用中添加它。使用自定义DBConnection类包装SQLiteConnection

由于我更经常地使用这个类,我想过创建一个自己的类,它负责处理所有事情。

现在,这是我的DB-类:

class DBConnection 
{ 

    public SQLiteConnection m_dbConnection; 

    public DBConnection() 
    { 
     Open(); 
    } 

    private void Open() 
    { 
     m_dbConnection = new SQLiteConnection("Data Source=Diary.sqlite;Version=3;"); 
     m_dbConnection.Open(); 
    } 

    public void Close() 
    { 
     m_dbConnection.Close(); 
    } 

} 

现在,在另一个Form,我试图访问它:

private void FrmLogin_Load(object sender, EventArgs e) 
    { 
     DBConnection DBConnection = new DBConnection(); 
     string sql = "SHOW TABLES"; 
     SQLiteCommand command = new SQLiteCommand(sql, DBConnection); 
     SQLiteDataReader reader = command.ExecuteReader(); 
     Console.WriteLine(reader); 
    } 

以下错误然而,这结束了:

Error CS1503 Argument 2: cannot convert from 'FFR2.DBConnection' to 'System.Data.SQLite.SQLiteConnection'

我试着在我的DBConnection类继承SQLiteConnection:

class DBConnection : SQLiteConnection但这并不正确。我想要一个类,它会自动打开数据库,在我的调用中关闭并根据需要发出命令,如示例中所示。你需要或者方法添加到您的DB类

public SQLIteCommand MakeCommand(string sql) 
{ 
    return new SqliteCommand(sql,m_dbConnection); 
} 

例如

感谢您的任何意见

+0

我创建了一个C#/ SQLite/NHiberate Web Forms项目,以解决连接问题。我在Github上完成了这个完成的项目,这个链接就是你所要求的。添加的项目是ORM/NHibernate https://github.com/RegencySoftware/SQLite-NHibernate-CSharp-Demo –

回答

1

I'm working on a learning project and I'm trying to get started with sqlite + C#. I found out that the SQLite-lib isn't a standard-lib, so I added it per reference.

注意确保你的意思到底是什么“标准-lib的”,但是从我了解他们的NuGet包,他们提供的DbConnection确实实现了IDbConnection接口和一般is an ADO.NET provider for SQLite

,如果你改变你的连接是一个SQLite连接您的代码应工作

var DBConnection = new SQLiteConnection("Data Source=Diary.sqlite;Version=3;"); 
    string sql = "SHOW TABLES;"; 
    DBConnection.Open(); 
    SQLiteCommand command = new SQLiteCommand(sql, DBConnection); 
    SQLiteDataReader reader = command.ExecuteReader(); 

注意:您应该处理您的连接,就像使用连接将声明包装到using声明一样简单。

using(var connection = new SQLiteConnection("Data Source=Diary.sqlite;Version=3;")) 
{ 
    connection.Open(); 
    var command = new SQLiteCommand(sql, DBConnection); 
    var reader = command.ExecuteReader(); 
    //do stuff 
} 

这确保您的连接在块执行后立即关闭。

+0

就像一个魅力! :) 谢谢 – DasSaffe

0

。或暴露的DbConnection到外面的世界

public DBConnection DB { get { return m_dbConnection;}} 
... 
    SQLiteCommand command = new SQLiteCommand(sql, myConn.DB);