2016-07-25 90 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);