Getting Started with SQLite and Visual Studio 2010

Experimenting with SQLite and C#, your first decision is which version of the overwhelming download options to choose. In my case, I got the sqlite-netFx35-static-binary-bundle-Win32-2008-[version number] running, while the unbundled package raised an error (sorry, can’t remember).

Once you get the correct package, we need a valid file path for our database:

var f = Path.Combine(
  Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), 
  "mydatabase.db");
var cn = new System.Data.SQLite.SQLiteConnection(
  (new System.Data.SQLite.SQLiteConnectionStringBuilder { DataSource = f })
    .ConnectionString);
cn.OpenAndReturn();

Next, we need to create the tables if they do not exist:

var tables = cn.GetSchema("Tables", new []{ null, null, "MyTableName", null});        

if (tables.Rows.Count == 0)
{
  var cmd = cn.CreateCommand();
  cmd.CommandText = "CREATE TABLE MyTableName ( ... columns ...)";
  cmd.ExecuteNonQuery();
}
Advertisements

One Response to Getting Started with SQLite and Visual Studio 2010

  1. […] I figured out how to create and access a SQLite database in C#, the obvious (for me, at least) next step was to use NHibernate for database […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: