0

I'm new to programming and my first project is connecting c# to sqlite and I have been successful connecting them.

The problem is that I have to always put the sqliteconnection con = new sqliteconnection("Data Source = sampledb.db;Version = 3");

The question is, can I just use a class where I could just put the sqliteconnection and just simply call it and can someone show me a sample code? thank you, your answers would be really much be appreciated,

btw I'm from the philippines, sorry for my english its not that good :)

Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
  • 1
    No, creating the connection just when needed and destroying it afterwards is the correct pattern to follow. Also for file based databases like SQLite. However, you could keep the connection string in the config file (`"Data Source = sampledb.db;Version = 3"`)and read the values from there – Steve Oct 09 '14 at 05:18

1 Answers1

0

Say if you're using a connection like this:

using (sqliteconnection con = new sqliteconnection("Data Source = sampledb.db;Version = 3")
{
...
}

You could put that in a function, eg:

public sqliteConnection GetConnection()
{
var con= new sqliteconnection(connectionString);
 try
 {
    con.Open();
 }
 catch (Exception ex)
 {
 }
return con;
}

And use the single function where you need it, eg:

using (var conn = this.GetConnection())
{
..
}
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
  • thank you sir jeremy for that answer, just one more question, how do I close that connection from that function,? or should I just create another function that closes that connection?? haha, I'm really confused – Leonard Andrew Mesiera Oct 11 '14 at 00:22
  • You could create another function that closes the connection and as a backup know that when the code execution exits the using statement it will Dispose the Connection object implicitly closing it. See here http://stackoverflow.com/questions/4389506/ado-net-closing-connection-when-using-using-statement – Jeremy Thompson Oct 11 '14 at 02:35
  • sir one more question, im really sorry, still is confusing to me, okay what I want to do is create a connection in the interface in c# where i could just call it but i'm really having trouble calling the connection from the interface sir, – Leonard Andrew Mesiera Oct 12 '14 at 02:32
  • Edit your question with additional information showing me what you are trying to do and I'll see if I can help – Jeremy Thompson Oct 12 '14 at 04:14
  • Edit your question to show us the code you have that doesn't work. – Jeremy Thompson Oct 12 '14 at 07:25
  • sqliteconnection con = new sqliteconnection("data source = sample.db; Version = 3;"); – Leonard Andrew Mesiera Oct 12 '14 at 19:13