Reputation: 2198
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.
Since I'm using this class more often, I thought about creating an own class, which takes care of everything.
Right now, this is my DB-class:
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();
}
}
Now, in another Form
, I'm trying to access it:
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);
}
This however ends up in the following error:
Error CS1503 Argument 2: cannot convert from 'FFR2.DBConnection' to 'System.Data.SQLite.SQLiteConnection'
I tried in my DBConnection-class to inherit the SQLiteConnection with this:
class DBConnection : SQLiteConnection
but that wasn't right as well. I'd like to have a class, which automatically opens the DB, closes on my call and make commands on demand like shown in the example.
Thanks for any advice
Upvotes: 1
Views: 1749
Reputation: 3231
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.
Note sure exactly what you mean by a "standard-lib" but from what I understand the DbConnection they provide in their nuget package does implement the IDbConnection
interface and in general is an ADO.NET provider for SQLite
if you change your connection to be a SQLite connection your code should work
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();
Note: you should be disposing your connections, it's as easy as wrapping the statements using the connection into a using
statement.
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
}
This makes sure your connection is closed immediately after execution of the block rather.
Upvotes: 1
Reputation: 50210
you need to either add methods to your DB class
public SQLIteCommand MakeCommand(string sql)
{
return new SqliteCommand(sql,m_dbConnection);
}
for example. Or expose the DBconnection to the outside world
public DBConnection DB { get { return m_dbConnection;}}
...
SQLiteCommand command = new SQLiteCommand(sql, myConn.DB);
Upvotes: 0