Get Started with SQLite and Visual Studio
By Peter Bromberg
How to get started using SQLite with Designer Support in Visual Studio
I've written here a number of times about SQLite and its features. The latest version of the ADO.NET SQLite Provider -by Robert Simpson
- features complete Visual Studio integration with all versions of Visual Studio-
2005, 2008, and 2010. This means you can create a new SQLite database file from
Server Explorer, create tables and indexes, and everything else you need to put
a SQLite database to work in your project.
SQLite, because of its small size (the provider is a mixed-mode assembly that includes
the C++ SQLite database engine), ease of deployment ("Plain old XCopy")
and speed, is ideal for small projects -- from a demo to even a full website.
The full assembly, System.Data.SQLite.DLL, is only 866Kb. When you install SQLite
the way I recommend for Visual Studio integration, it will be installed in the
GAC. However, you can easily distribute the binary along with your project -
that's a separate download. There is no need to have the assembly GAC-ed in order
for it to work.
For this example, we'll install SQLite, and from within Visual Studio, we'll create
a new database and a single table, PERSONS, to represent a contact list. We'll
provide a simple Windows Forms front end that allows you to enter a new row in
the table, and we'll also have a DataGridView that can display existing rows
from the database.
So first, download the "Installer" version from the latest file releases. The one that I got most recently is "SQLite-1.0.65.0-setup.exe".
Run the installer, and you should be prompted with checkboxes to enable Visual
Studio integration with any of Visual Studio 2005, 2008, or 2010. Now that SQLite
is installed, we can get started.
Create a new Windows Forms application, and add four textboxes and four labels for
FirstName, LastName, Email and Phone as shown below. Add two buttons, one to
SAVE and the other to DISPLAY. Finally, add a DataGridView on the right side
to display results from queries.

Now lets create our database and our table, along with a SQLiteConnection. Open up
Server Explorer. In the Data Connections Node, right click and choose "Add
Connection". Change the Data Source to "SQLite Database File (.NET
Framework Data Provider for SQLite)". Under "Database", click
the "New" Button. Under File Name, enter "TEST.db3" and click
"SAVE". Now click "Test Connection" to verify.
Now, open up the ToolBox and down near the bottom, under SQLite, you'll see "SQLite
Connection" Drag one of these onto your component tray area at the bottom
of your Form's Design window.
Now, let's create our PERSONS table. Back in Server Explorer, highlight the Tables
node, right click, and choose "Add new Table". Create a table with
columns that look like this:

Save your work - we are ready to code.
Our "SAVE" button click code looks like the following:
private void button1_Click(object sender, EventArgs e)
{
SQLiteTransaction trans;
string SQL = "INSERT INTO PERSONS (ID, FIRSTNAME,LASTNAME,EMAIL,PHONE) VALUES";
SQL += "(@ID, @firstname, @lastname, @email, @phone)";
SQLiteCommand cmd = new SQLiteCommand(SQL);
cmd.Parameters.AddWithValue("@ID", Guid.NewGuid());
cmd.Parameters.AddWithValue("@firstname", this.txtFirst.Text);
cmd.Parameters.AddWithValue("@lastname", this.txtLast.Text);
cmd.Parameters.AddWithValue("@email", this.txtEmail.Text);
cmd.Parameters.AddWithValue("@phone", this.txtPhone.Text);
cmd.Connection = sqLiteConnection1;
sqLiteConnection1.Open();
trans = sqLiteConnection1.BeginTransaction();
int retval = 0;
try
{
retval= cmd.ExecuteNonQuery();
if (retval == 1)
MessageBox.Show("Row inserted!");
else
MessageBox.Show("Row NOT inserted.");
}
catch (Exception ex)
{
trans.Rollback();
}
finally
{
trans.Commit();
cmd.Dispose();
sqLiteConnection1.Close();
}
}
Finally, our "DISPLAY" button click handler code looks like this:
private void button2_Click(object sender, EventArgs e)
{
string SQL = "SELECT * FROM PERSONS";
SQLiteCommand cmd = new SQLiteCommand(SQL);
cmd.Connection = sqLiteConnection1;
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
da.Fill(ds);
DataTable dt = ds.Tables[0];
this.dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
}
finally
{
cmd.Dispose();
sqLiteConnection1.Close();
}
}
That's all you need, run the app and try putting in one or two entries. Then, click
the Display button to show them in the grid. Congratulations. You've created
your first SQLite Application! One important note: You will see orders of magnitude
in performance improvement if you can get into the habit of wrapping all your
SQLite work in transactions. The code for the insert operation illustrates how
to do this.
You can download the full source for a Visual Studio 2008 Solution here.
Popularity (19102 Views)
 |
| Biography - Peter Bromberg |
Peter Bromberg is a C# MVP, MCP, and .NET expert who has worked in banking, financial and telephony for over 20 years. Pete focuses exclusively on the .NET Platform, and currently develops SOA and other .NET applications for a Fortune 500 clientele. Peter enjoys producing digital photo collage with Maya,playing jazz flute, the beach, and fine wines. You can view Peter's UnBlog and IttyUrl sites.
|  |
|
|
Article Discussion: Get Started with SQLite and Visual Studio
David Fort replied
to Peter Bromberg at Tuesday, October 12, 2010 9:17 AM
Thanks for great article. I found it necessary to close and re-open VS2008 in order to get the second page of the Add Connection dialog, where "New ..." hides. Otherwise, just got a prompt for Connection String. Just thought I'd pass it along in case it puzzles others as it did me.
David Fort replied
to David Fort at Tuesday, October 12, 2010 9:17 AM
here:
catch (Exception ex)
{
trans.Rollback();
}
finally
{
trans.Commit();
it seems that if you catch an exception, for example for forgetting to change the default Table name from Table1 to PERSONS, then the Rollback() sets the connection to null, so the trans.Commit in finally throws another exception.
i.e. it seems that you shouldn't Commit after you Rollback.
(and also note that after you put sqLiteConnection1 in your component bucket by dragging it from Toolbox onto Form, you have to configure its ConnectionString property.
Francisco replied
to Peter Bromberg at Tuesday, October 12, 2010 9:17 AM
Hi!
Is it possible to execute consecutive queries without opening and closing the connection?
Thanks
Peter Bromberg replied
to Francisco at Tuesday, October 12, 2010 9:17 AM
SQLite provider uses connection pooling just like any other ADO.NET provider. Best practice is to open the connection just before issuing a command and close it immediately thereafter. You can issue multiple commands on an open connection, preferably within a transaction.
Francisco replied
to Peter Bromberg at Tuesday, October 12, 2010 9:17 AM
Hi again!
First, thanks for your reply. I´ve tested the diference between one insert per transaction and 100.000 (I have to migrate a db and one of the tables has 2.330.000 rows).
I recommend to batch 100.000 operations per transaction if possible because it´s 400x faster.
Thanks again, you really help me to start using SQLite.
Suraj replied
to Francisco at Tuesday, October 12, 2010 9:17 AM
Hi
Thanks for the information...
I want to ask about setup file. how to create setup file with SQLite database so that if I installed it on some other computer so that database file should be present on same computer And how to give database file path??
Thank you in advance... :)
Derek replied
to David Fort at Tuesday, October 12, 2010 9:17 AM
Hi, I have closed and re-opened visual studio, but I continue to get a connection string screen when I try to add database SQLite, and if I hit ok, it gives me an error (Cannot load file or assembly 'Microsoft.VisualStudio.Data, Version-9.0.0.0, Culture=Neutral, PublicKeytoken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest does not match the assembly reference.) Is this because I am in Visual Studio 10 and must use 8 instead? Or is there some other advice ? Thanks.
David Fort replied
to Derek at Tuesday, October 12, 2010 9:17 AM
Don't know, but fwiw, I was using VS2008 at the time of my previous post.
Rabishan replied
to Peter Bromberg at Tuesday, October 12, 2010 9:17 AM
in my data connection when i right click it says no command available. what maybe the problem. i have installed the sqlite as described by you. is it the problem of visual studio. btw i have visual studio 2010 express.
Anat Shimony replied
to Peter Bromberg at Tuesday, October 12, 2010 9:17 AM
Peter,
First great explanation.
I followed your exmpale, using VS2010, and I'm getting the following error message during debug -
An unhandeled exception of type 'System.IO.FileLoadException' occured in SQLiteForms.exe.
Additional information:Mixed mode assembly is built againt version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.
Appreciate any thought or ideas on the issue. Thx, Anat
Peter Bromberg replied
to Anat Shimony at Tuesday, October 12, 2010 9:17 AM
Go get the latest versions of SQLite ADO.NET provided. This is a very old article.
Ostorlabi Ostor replied
to Peter Bromberg at Tuesday, October 12, 2010 9:17 AM
Hi,
Thank you for this article, I have error exception in line trans.commit()
No connection associated with this transaction commit !!!
Could you help me please?
Ostorlabi Ostor replied
to Ostorlabi Ostor at Tuesday, October 12, 2010 9:17 AM
That's ok, I had to create "cmd.Transaction = trans" after "trans = sqliteconnection1.BeginTransaction();"
But the problem now is that I can't save my information and the button is still maintained!?