You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#应用连接SQLite方法及可跨机运行本地数据库实现咨询

嘿,我完全理解你的困扰——SQL Server确实不适合这种需要随处运行的桌面应用,而SQLite正是解决这个问题的完美方案!下面我一步步给你讲清楚怎么实现:

解决方案:用SQLite构建可跨电脑运行的C#数据存储应用

一、为什么选SQLite?

  • 它是文件型关系数据库:不需要单独安装数据库服务器,整个数据库就是一个.db文件,直接和你的应用程序打包在一起就行
  • 轻量级+跨平台:支持Windows、macOS、Linux,完美满足你“任意电脑都能运行”的需求
  • 兼容标准SQL语法:和你熟悉的SQL Server操作逻辑接近,学习成本极低

二、具体实现步骤

1. 安装SQLite NuGet包

在你的C#项目(WinForms、WPF、Console App都适用)里,通过NuGet安装核心依赖:

  • Microsoft.Data.Sqlite:微软官方提供的SQLite数据访问库,和ADO.NET兼容,推荐用这个
  • (可选)System.Data.SQLite:如果你习惯用传统ADO.NET方式也可以选它

操作方式:右键项目 → 管理NuGet程序包 → 搜索并安装上述包

2. 自动创建数据库与表

第一次启动应用时,如果数据库文件不存在,我们让程序自动创建它和需要的用户表。比如创建一个Users表来存储用户数据:

using Microsoft.Data.Sqlite;
using System.IO;
using System;

// 数据库文件路径,默认放在应用程序目录下的UserData.db
string dbPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UserData.db");
string connectionString = $"Data Source={dbPath};";

// 创建连接并初始化表
using (SqliteConnection connection = new SqliteConnection(connectionString))
{
    connection.Open();
    
    // 创建Users表的SQL(如果不存在就创建)
    string createTableSql = @"
        CREATE TABLE IF NOT EXISTS Users (
            Id INTEGER PRIMARY KEY AUTOINCREMENT,
            Username TEXT NOT NULL,
            Phone TEXT,
            CreatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
        );";
    
    using (SqliteCommand command = new SqliteCommand(createTableSql, connection))
    {
        command.ExecuteNonQuery();
    }
}

3. 实现用户数据输入与存储

写一个方法来插入用户数据,注意用参数化查询防止SQL注入:

public void SaveUser(string username, string phone)
{
    string dbPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UserData.db");
    string connectionString = $"Data Source={dbPath};";
    
    using (SqliteConnection connection = new SqliteConnection(connectionString))
    {
        connection.Open();
        
        string insertSql = @"
            INSERT INTO Users (Username, Phone)
            VALUES (@Username, @Phone);";
        
        using (SqliteCommand command = new SqliteCommand(insertSql, connection))
        {
            // 绑定参数,避免SQL注入
            command.Parameters.AddWithValue("@Username", username);
            command.Parameters.AddWithValue("@Phone", phone);
            
            command.ExecuteNonQuery();
        }
    }
}

4. 启动时加载留存数据

写一个查询方法,在程序启动时调用,把之前存储的用户数据读出来:

// 先定义一个User实体类
public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public string Phone { get; set; }
    public DateTime CreatedAt { get; set; }
}

// 查询所有用户的方法
public List<User> LoadAllUsers()
{
    List<User> userList = new List<User>();
    string dbPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UserData.db");
    string connectionString = $"Data Source={dbPath};";
    
    using (SqliteConnection connection = new SqliteConnection(connectionString))
    {
        connection.Open();
        
        string selectSql = "SELECT Id, Username, Phone, CreatedAt FROM Users;";
        
        using (SqliteCommand command = new SqliteCommand(selectSql, connection))
        {
            using (SqliteDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    User user = new User
                    {
                        Id = reader.GetInt32(0),
                        Username = reader.GetString(1),
                        Phone = reader.IsDBNull(2) ? null : reader.GetString(2),
                        CreatedAt = reader.GetDateTime(3)
                    };
                    userList.Add(user);
                }
            }
        }
    }
    return userList;
}

5. 部署注意事项

  • 发布应用时,把生成的UserData.db文件和你的exe放在同一目录(如果程序启动时检测到文件不存在会自动创建)
  • 推荐选择独立部署(Self-contained)模式发布,确保所有依赖项都打包在内,用户不需要额外安装.NET运行时

三、额外小提示

  • 如果需要更复杂的数据操作,可以搭配Entity Framework Core(安装Microsoft.EntityFrameworkCore.Sqlite包),能大幅简化CRUD代码
  • 记得定期备份UserData.db文件,避免数据丢失

内容的提问来源于stack exchange,提问作者Aleksa Djuric

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:52:41