Using SQLite Database with C# in Visual Studio 2010
SQLite Overview
SQLite is a lightweight, ACID-compliant relational database management system contained within a small C libray. Originally created by D. Richard Hipp as a public domain project, SQLite was designed for embedded applications and has been widely adopted in numerous embedded products. The database requires only a few hundred kilobytes of memory, supports major operating systems including Windows, Linux, and Unix, and interfaces with multiple programming languages such as Tcl, C#, PHP, and Java. SQLite achieves faster performance compared to MySQL and PostgreSQL. The initial alpha version released in May 2000, and the current version is SQLite 3.
Environment Setup
SQLite Shell Installation
Download the precompiled binaries for Windows from the official SQLite website. Extract the archive and add the extraction path to your system's PATH environment variable to enable command-line access from any directory.
.NET Provider Download
Obtain the System.Data.SQLite provider compatible with your .NET framework version. For Visual Studio 2010 with .NET Framework 4.0, download the following installer:
sqlite-netFx40-setup-bundle-x86-2010-1.0.94.0.exe
Command-Line Database Operations
Creating a Database
sqlite3 d:/test.db;
Creating a Table
CREATE TABLE testtable (id INTEGER PRIMARY KEY, testname VARCHAR(100));
Basic Operations
- Insert Data:
INSERT INTO tablename VALUES (...) - Query Data:
SELECT * FROM tablename - Exit:
.quit - Help:
.help
C# Implementation
Project Configuration
After installing System.Data.SQLite, create a new Console Application in Visual Studio 2010. Add references to the following assemblies:
System.Data.SQLite.dllSystem.Data.SQLite.Linq.dll
Database and Connection Setup
using System;
using System.Data;
using System.Data.SQLite;
using System.IO;
namespace SQLiteDemo
{
class Program
{
static void Main(string[] args)
{
string dbPath = @"D:\app_data\sample.db";
// Create database file if not exists
if (!File.Exists(dbPath))
{
SQLiteConnection.CreateFile(dbPath);
}
// Configure connection string
var connectionBuilder = new SQLiteConnectionStringBuilder
{
DataSource = dbPath,
Password = "pguser",
Pooling = true
};
using (var connection = new SQLiteConnection(connectionBuilder.ToString()))
{
connection.Open();
// Create table
const string createTableSql = @"
CREATE TABLE IF NOT EXISTS Xlog (
logtype VARCHAR(20),
content VARCHAR(400)
)";
using (var createCmd = new SQLiteCommand(createTableSql, connection))
{
createCmd.ExecuteNonQuery();
}
// Insert data
const string insertSql = "INSERT INTO Xlog (logtype, content) VALUES (@type, @content)";
using (var insertCmd = new SQLiteCommand(insertSql, connection))
{
insertCmd.Parameters.AddWithValue("@type", "test1");
insertCmd.Parameters.AddWithValue("@content", "test2");
insertCmd.ExecuteNonQuery();
}
// Query data
const string selectSql = "SELECT logtype, content FROM Xlog";
using (var selectCmd = new SQLiteCommand(selectSql, connection))
using (var dataReader = selectCmd.ExecuteReader())
{
var output = new System.Text.StringBuilder();
while (dataReader.Read())
{
string logType = dataReader.GetString(0);
string content = dataReader.GetString(1);
output.AppendLine($"Type: {logType}, Content: {content}");
}
Console.WriteLine(output.ToString());
}
}
Console.WriteLine("Database operations completed successfully.");
Console.ReadKey();
}
}
}
Key Implementation Details
Connection Management: Always use the using statement to ensure proper disposal of database connections, even when excepsions occur.
Parameter Binding: Use parameterized queries instead of string concatenation to prevent SQL injection vulnerabilities.
Transaction Support: For batch operations, wrap multiple commands within a transaction:
using (var transaction = connection.BeginTransaction())
{
try
{
// Execute multiple commands
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
Data Reader: The SQLiteDataReader provides forward-only, read-only access to query results. For cached or disconnected scenarios, populate a DataSet or DataTable instead.