在C#中使用SQLite数据库

轻量级桌面程序数据库不太适合用SQLServer、MySQL之类的重量级数据库,嵌入式数据库更好。在对比Access、SQLite、Firebird数据库后发现SQLite较另外两个有较多优点。

环境:.NET Framework 3.5、windows11 64位、Visual Studio 2010.

C#使用SQLite需要从SQLite官网下载DLL组件。

我是windows11,64位的开发环境,最开始下载的64位的,结果运行时报异常。通过查资料,情况比较复杂(参考:https://blog.51cto.com/xxjjing/5804868),遂重新下载了32位的包:sqlite-netFx35-binary-Win32-2008-1.0.117.0

下载地址:https://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki

下载后将包解压放到一个固定目录,需要依赖System.Data.SQLite.dll和SQLite.Interop.dll这两个文件,

在项目里右键项目 > 添加引用 > 选“浏览”选项卡,找到解压后的目录,引入System.Data.SQLite.dll,另一个文件SQLite.Interop.dll不可以通过引用方式添加,必须只能复制文件到运行目录下,通过调试发现程序会自动把System.Data.SQLite.dll也复制到运行目录下,System.Data.SQLite.dll和SQLite.Interop.dll文件会在一起。(尝试过直接复制这两个文件到程序的运行目录下不可行,Visual Studio里不管怎么刷新项目的引用列表都不会出现这两个文件,运行会报错。)

C# 中使用SQLite示例:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Data.SQLite;

namespace SQLiteTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Console.WriteLine("SQL Lite 数据库试验");
            // 连接数据库,FailIfMissing=false时若文件不存在会自动创建
            string connStr = "Data Source=test.db;Version=3;Pooling=true;FailIfMissing=false;";
            SQLiteConnection conn = new SQLiteConnection(connStr);
            conn.Open();

            //在指定数据库中创建一个table
            string sql = "create table highscores (name varchar(20), score int)";
            SQLiteCommand command = new SQLiteCommand(sql, conn);
            command.ExecuteNonQuery();

            // 插入一些数据
            sql = "insert into highscores (name, score) values ('Me', 3000)";
            command = new SQLiteCommand(sql, conn);
            command.ExecuteNonQuery();

            sql = "insert into highscores (name, score) values ('Myself', 6000)";
            command = new SQLiteCommand(sql, conn);
            command.ExecuteNonQuery();

            sql = "insert into highscores (name, score) values ('And I', 9001)";
            command = new SQLiteCommand(sql, conn);
            command.ExecuteNonQuery();

            // 查询数据
            sql = "select * from highscores order by score desc";
            command = new SQLiteCommand(sql, conn);
            SQLiteDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                Console.WriteLine("Name: " + reader["name"] + "\tScore: " + reader["score"]);
            }
        }
    }
}

 

 一般建表使用文本文件,不使用代码建(build.sql):

-- admin表
create table admin (
  id nvarchar(32) primary key,
  admin_account nvarchar(32) not null,
  password nvarchar(32) not null
);

-- file表
create table file (
  id nvarchar(32) primary key,
  user_account nvarchar(32) not null,
  user_name nvarchar(32) not null,
  file_path nvarchar(256) not null,
  upload_start_time timestamp,
  upload_end_time timestamp,
  upload_ip nvarchar(20),
  file_md5 nvarchar(32),
  file_size integer,
  file_suffix nvarchar(4)
);

-- file_remove_history表
create table file_remove_history (
  id nvarchar(32) primary key,
  user_account nvarchar(32) not null,
  user_name nvarchar(32) not null,
  file_path nvarchar(256) not null,
  upload_start_time timestamp,
  upload_end_time timestamp,
  upload_ip nvarchar(20),
  file_md5 nvarchar(32),
  file_size integer,
  file_suffix nvarchar(4),
  remove_user nvarchar(20),
  remove_time timestamp
);

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Data.SQLite;
using System.IO;

namespace U8FileBackupServer
{
    public partial class Form1 : Form
    {
        
        string dbFile = System.Environment.CurrentDirectory + "\\xxx.db";

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            if (!File.Exists(dbFile))
            {
                Console.WriteLine("文件不存在,执行创建。");
                SQLiteConnection.CreateFile(dbFile);
                // 连接数据库,FailIfMissing=false时若文件不存在也会自动创建
                SQLiteConnection conn = new SQLiteConnection("Data Source=" + dbFile + ";Version=3;Pooling=true;FailIfMissing=false;");
                conn.Open(); // 打开连接

                // 建表
                string sqlText = new StreamReader(System.Environment.CurrentDirectory + "\\build.sql").ReadToEnd();
                Console.WriteLine("= = = = = = = = = = = = = = = = = = = = = = = = =");
                Console.WriteLine(sqlText);
                Console.WriteLine("= = = = = = = = = = = = = = = = = = = = = = = = =");
                SQLiteCommand cmd = new SQLiteCommand(sqlText, conn);
                cmd.ExecuteNonQuery();
                conn.Close(); // 关闭连接
            }
            
            SQLiteConnection conn1 = new SQLiteConnection("Data Source=" + dbFile + ";Version=3;Pooling=true;FailIfMissing=true;");
            conn1.Open();
        // 插入一些数据
            string sql = "insert into admin (id, admin_account, password) values ('111', '管理员', 'admin')";
            SQLiteCommand command = new SQLiteCommand(sql, conn1);
            command.ExecuteNonQuery();
        // 查询数据
            sql = "select * from admin";
            command = new SQLiteCommand(sql, conn1);
            SQLiteDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                Console.WriteLine("admin_account: " + reader["admin_account"] + "\tpassword: " + reader["password"]);
            }
conn1.Close(); } } }

 

更多参考资料:

原文链接:https://www.cnblogs.com/jsper/p/17346758.html

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:在C#中使用SQLite数据库 - Python技术站

(0)
上一篇 2023年4月27日
下一篇 2023年4月27日

相关文章

  • 在.NET Core使用 HttpClient 的正确方式

    前言 HttpClient 是 .NET Framework、.NET Core 或 .NET 5以上版本中的一个类,用于向 Web API 发送 HTTP 请求并接收响应。它提供了一些简单易用的方法,如 GET、POST、PUT 和 DELETE,可以很容易地构造和发送 HTTP 请求,并处理响应数据。它是我们比较常用的官方HTTP请求组件,那么你们都正确…

    C# 2023年4月17日
    00
  • .NetCore利用BlockingCollection实现简易消息队列

    .NET Core利用BlockingCollection实现简易消息队列 在.NET Core应用程序中,我们可以使用BlockingCollection类来实现简易消息队列。本攻略将详细介绍如何使用BlockingCollection类来实现简易消息队列,并提供两个示例说明。 BlockingCollection类 BlockingCollection类…

    C# 2023年5月17日
    00
  • C# Xamarin利用ZXing.Net.Mobile进行扫码的方法

    以下是C# Xamarin利用ZXing.Net.Mobile进行扫码的方法的完整攻略: 1. ZXing.Net.Mobile的介绍 1.1 什么是ZXing.Net.Mobile ZXing.Net.Mobile是一款基于ZXing的二维码扫描框架,支持多种平台,包括Xamarin.Android、Xamarin.iOS、Windows Phone、Wi…

    C# 2023年6月3日
    00
  • C#微信公众号开发之自定义菜单

    C#微信公众号开发之自定义菜单 简介 微信公众号是微信平台提供给开发者的一款应用型产品,它提供给企业或个人一个与互联网用户交互的应用平台。 微信公众号开发的菜单,提供给用户一个便捷来访问公众号的方式,菜单可以是文字、图文等形式。在这篇文章中,我们将介绍如何使用C#实现微信公众号的自定义菜单。 实现步骤 1. 注册成为微信开发者 在微信公众号开发之前,我们需要…

    C# 2023年6月1日
    00
  • C# Linq的ToArray()方法 – 将序列转换为数组

    C#中Linq的ToArray()方法可将元素集合转化为数组形式,其函数声明如下: public static TSource[] ToArray<TSource>(this IEnumerable<TSource> source); ToArray()方法接收一个IEnumerable集合对象参数,并返回其对应的TSource类型数…

    C# 2023年4月19日
    00
  • C#入参使用引用类型要加ref的原因解析

    C#中,我们可以将变量传递给方法,以便在方法内部使用。但是在使用引用类型作为参数时,我们需要使用关键字ref。那么为什么要这么做呢?接下来就进行详细讲解。 1. 值类型和引用类型的区别 在开始解释原因之前,我们必须要先理解值类型和引用类型的不同之处。在C#中,值类型包括int、double、bool等基本数据类型,而引用类型则包括string、object和…

    C# 2023年6月1日
    00
  • asp.net使用ashx生成图形验证码的方法示例

    下面我将为您详细讲解如何使用ashx生成图形验证码的方法。 1.什么是ASHX? ASHX 全称是“ASP.NET Generic Handler”,是一种特殊的文件类型,可以处理的内容不止HTML,还可以处理图片、脚本、样式表等类型。 2. ashx生成图形验证码的过程 使用 ASHX 生成图形验证码的过程分为以下几个步骤: 1)创建 ASHX 文件 在 …

    C# 2023年5月31日
    00
  • C# 使用HttpClient模拟请求的案例

    我可以为您详细讲解“C# 使用HttpClient模拟请求的案例”的完整攻略。下面是具体的步骤: 1、安装HttpClient库 在C#中,使用HttpClient需要安装相应的库文件,可以使用NuGet包管理器来安装。具体操作如下: 打开Visual Studio。 在解决方案资源管理器中右键单击项目,然后选择管理NuGet程序包。 在NuGet程序包管理…

    C# 2023年5月31日
    00
合作推广
合作推广
分享本页
返回顶部