Developers often need small tools to automate everyday tasks. These tools might read configuration files, track development activities, store project information, manage build results, or maintain a local history of commands.
A common approach is to build a small application that stores information in JSON files or relies on an external database server. JSON works well for simple configuration and small amounts of data, but it becomes harder to manage when the application needs filtering, relationships, updates, or reliable concurrent access. An external database server can solve these problems, but it introduces additional installation and configuration requirements.
SQLite provides a practical alternative. It is a lightweight relational database that stores information in a local file. It does not require a separate database server, making it suitable for desktop utilities, command-line tools, developer assistants, and local automation applications.
.NET provides several ways to work with SQLite. In this article, we will build a small command-line developer tool using C# and SQLite. The application will maintain a local project task list, allowing developers to add tasks, view pending work, mark tasks as completed, and retain the information between application executions.
The example will also cover database initialization, parameterized queries, repository design, error handling, and practical considerations for distributing local developer tools.
Why Use SQLite for a Local Developer Tool?
A local developer tool should be easy to install, configure, and use. Developers should not need to configure a database server just to maintain a small collection of project-related information.
SQLite provides several advantages for this type of application:
It stores data in a single database file.
It does not require a separate database server.
It supports SQL queries, indexes, constraints, and transactions.
It works well with small and medium-sized local datasets.
It can be distributed alongside a .NET application.
It supports structured data without requiring a remote service.
Consider a command-line tool that tracks development tasks. It may need to store a task title, description, creation date, and completion status.
A JSON file could store these records, but retrieving only incomplete tasks or updating a specific record requires additional application logic.
With SQLite, the application can use SQL directly:
SELECT *
FROM Tasks
WHERE IsCompleted = 0
ORDER BY CreatedAt DESC;The database handles filtering and ordering, while the application focuses on its actual functionality.
SQLite is not a replacement for every database system. Applications requiring multiple remote users, centralized database administration, or high-volume concurrent writes may need a server-based database. However, for a self-contained developer utility, SQLite is often a good fit.
Creating the .NET Project
Start by creating a console application:
dotnet new console -n LocalDeveloperTool
cd LocalDeveloperToolInstall the Microsoft.Data.Sqlite package:
dotnet add package Microsoft.Data.SqliteThis package provides the ADO.NET provider used to connect to SQLite databases from .NET applications.
Create the following project structure:
LocalDeveloperTool/
|
|-- Models/
| |-- DeveloperTask.cs
|
|-- Data/
| |-- DatabaseInitializer.cs
| |-- TaskRepository.cs
|
|-- Services/
| |-- TaskService.cs
|
|-- Program.cs
|
|-- local-dev.dbThe database file will be created automatically when the application initializes the SQLite connection.
For a real application, keep generated database files outside the source-controlled project directory unless there is a specific reason to include a sample database.
Defining the Task Model
Start by creating a model that represents a task.
Create Models/DeveloperTask.cs:
namespace LocalDeveloperTool.Models;
public class DeveloperTask
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public bool IsCompleted { get; set; }
public DateTime CreatedAt { get; set; }
}The model contains the information that the application needs to store.
The Id property identifies each task. The Title and Description properties contain task information, while IsCompleted indicates whether the task has been finished.
CreatedAt records when the task was added.
Keeping the model separate from database operations makes the application easier to maintain. If the database schema changes later, the application does not need to place SQL logic inside every command handler.
Initializing the SQLite Database
The application needs to create the database table before storing tasks.
Create Data/DatabaseInitializer.cs:
using Microsoft.Data.Sqlite;
namespace LocalDeveloperTool.Data;
public class DatabaseInitializer
{
private readonly string _connectionString;
public DatabaseInitializer(string databasePath)
{
_connectionString =
new SqliteConnectionStringBuilder
{
DataSource = databasePath
}.ToString();
}
public string ConnectionString => _connectionString;
public void Initialize()
{
using var connection =
new SqliteConnection(_connectionString);
connection.Open();
using var command = connection.CreateCommand();
command.CommandText = """
CREATE TABLE IF NOT EXISTS Tasks
(
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Title TEXT NOT NULL,
Description TEXT,
IsCompleted INTEGER NOT NULL DEFAULT 0,
CreatedAt TEXT NOT NULL
);
""";
command.ExecuteNonQuery();
}
}The initializer creates a connection using the supplied database file path.
When the application opens the connection for the first time, SQLite creates the database file if it does not already exist.
The CREATE TABLE IF NOT EXISTS statement ensures that the Tasks table is created only when it is missing.
This is useful for a small initial implementation. However, as an application grows, database schema changes should be handled through an explicit migration mechanism rather than adding unrelated table creation statements to the startup process.
Creating the Task Repository
The repository will contain the SQL operations required by the application.
Create Data/TaskRepository.cs:
using LocalDeveloperTool.Models;
using Microsoft.Data.Sqlite;
namespace LocalDeveloperTool.Data;
public class TaskRepository
{
private readonly string _connectionString;
public TaskRepository(string connectionString)
{
_connectionString = connectionString;
}
public int Add(DeveloperTask task)
{
using var connection =
new SqliteConnection(_connectionString);
connection.Open();
using var command = connection.CreateCommand();
command.CommandText = """
INSERT INTO Tasks
(Title, Description, IsCompleted, CreatedAt)
VALUES
($title, $description, $completed, $createdAt);
SELECT last_insert_rowid();
""";
command.Parameters.AddWithValue(
"$title",
task.Title
);
command.Parameters.AddWithValue(
"$description",
task.Description
);
command.Parameters.AddWithValue(
"$completed",
task.IsCompleted ? 1 : 0
);
command.Parameters.AddWithValue(
"$createdAt",
task.CreatedAt.ToString("O")
);
return Convert.ToInt32(
command.ExecuteScalar()
);
}
public List<DeveloperTask> GetAll()
{
var tasks = new List<DeveloperTask>();
using var connection =
new SqliteConnection(_connectionString);
connection.Open();
using var command = connection.CreateCommand();
command.CommandText = """
SELECT
Id,
Title,
Description,
IsCompleted,
CreatedAt
FROM Tasks
ORDER BY CreatedAt DESC;
""";
using var reader = command.ExecuteReader();
while (reader.Read())
{
tasks.Add(new DeveloperTask
{
Id = reader.GetInt32(0),
Title = reader.GetString(1),
Description = reader.IsDBNull(2)
? string.Empty
: reader.GetString(2),
IsCompleted = reader.GetInt32(3) == 1,
CreatedAt = DateTime.Parse(
reader.GetString(4),
null,
System.Globalization.DateTimeStyles.RoundtripKind
)
});
}
return tasks;
}
public bool MarkCompleted(int taskId)
{
using var connection =
new SqliteConnection(_connectionString);
connection.Open();
using var command = connection.CreateCommand();
command.CommandText = """
UPDATE Tasks
SET IsCompleted = 1
WHERE Id = $id;
""";
command.Parameters.AddWithValue("$id", taskId);
return command.ExecuteNonQuery() > 0;
}
}The repository provides three operations.
Add inserts a new task and returns its generated ID. GetAll retrieves the saved tasks, while MarkCompleted updates the completion status of a specific task.
Notice that the queries use parameters such as $title and $id instead of inserting values directly into SQL strings.
Parameterized queries are important even in local tools. They prevent user-provided values from changing the structure of SQL statements and help avoid SQL injection vulnerabilities.
The repository also opens and disposes its own connection for each operation. SQLite connections are lightweight, and this approach keeps the example simple while avoiding a connection remaining open unnecessarily.
Adding the Application Service
The service layer will handle basic application rules before calling the repository.
Create Services/TaskService.cs:
Join the conversation! Your thoughts help the community grow.