This tutorial will teach you how to create and connect to an sqlite database in C#. You will also learn how to create and modify tables and how to execute sql queries on the database and how to read the returned results.
I’ll assume that you’re already familiar with sql and at least have some knowledge of how it works (for example: what to expect as a result from “select * from table1″ )
There will probably be two parts,with the first one discussing the basics needed to do pretty much anything,and in the second part I’ll discuss some miscellaneous subjects like how to parameterize your queries to make them much faster and safer.
Let’s get started.
Create a standard C# console project.
Since we’re working in C# we’ll be using the System.Data.sqlite library. This library is not a standard library (packaged with .NET for example) so we’ll need to download it. It is being developed by the people who’re also working on the (original) sqlite.
All you’ll need are two files,a .dll and a .xml file for some documentation. These files are available for download at the end of this article,you can also download these from theirwebsite,but you’ll also get some files that you don’t need.
Put these files in the folder of your project and add an assembly reference to the .dll. Just browse to System.Data.sqlite.dll and select it.
Now add using System.Data.sqlite; to the usings and you’re done. You’ve successfully added the sqlite library to you project!
Creating a database file:
You usually don’t need to create a new database file,you work with an existing one,but for those cases where you do need to create a brand new one,here’s the code:
Connecting to a database:
Before you can use the database,you’ll need to connect to it. This connection is stored inside a connection object. Every time you interact with the database,you’ll need to provide the connection object. Therefore,we’ll declare the connection object as a member variable.
1
|
sqliteConnection m_dbConnection;
|
When creating a connection,we’ll need to provide a “connection string” this string can contain information about the… connection. Things like the filename of the database,the version,but can also contain things like a password,if it’s required.
You can find a few of these at:http://www.connectionstrings.com/sqlite
The first one is good enough to get our connection up and running,so we get:
1