SQLite NET

C# 程序中使用 SQLite 数据库

复制代码
using System;
using System.Data;
using System.Data.SQLite;

//C# 使用 SQLite 数据测试程序
public class Program
{
    public static void Main(string[] args)
    {
        using (SQLiteConnection con = new SQLiteConnection("Data Source=c:\\test.db3;Pooling=true;FailIfMissing=false"))
        {
            //打开数据库文件 c:\\test.db3,不存在则创建
            con.Open();

            using (SQLiteCommand cmd = new SQLiteCommand())
            {
                cmd.Connection = con;

                //检查是否存在表 test,不存在则创建
                Boolean testTableExists = false;
                cmd.CommandText = "SELECT * FROM sqlite_master WHERE type='table' and name='test'";
                using(SQLiteDataReader dr = cmd.ExecuteReader())
                {
                    if (dr.Read())
                    {
                        testTableExists = true;
                    }
                }
                if (!testTableExists)
                {
                    cmd.CommandText = "CREATE TABLE [test] (id int, name nvarchar(20))";
                    cmd.ExecuteNonQuery();
                }

                //清空 test 表
                cmd.CommandText = "DELETE FROM [test]";
                cmd.ExecuteNonQuery();

                //插入测试数据
                for (int i = 1; i <= 5; i++)
                {
                    cmd.CommandText = string.Format("INSERT INTO [test] VALUES ({0}, '中文测试')", i);
                    cmd.ExecuteNonQuery();
                }

                //读取数据
                cmd.CommandText = "SELECT * FROM [test]";
                using (SQLiteDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                {
                    while (dr.Read())
                    {
                        Console.WriteLine("第{0} 条:{1}", dr.GetValue(0), dr.GetString(1));
                    }
                }
            }
        }

        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }
}

参考:

相关推荐
jiayou6415 小时前
KingbaseES 表级与列级加密完全指南
数据库·后端
GBASE1 天前
G术时刻 |GBase 8s数据库事务并发控制之封锁技术介绍(下)
数据库
xiezhr2 天前
逛GitHub发现了一款免费的带AI功能的数据库管理工具
数据库·ai编程·dba
吃糖的小孩3 天前
给 QQ AI 机器人设计“可控记忆”:会话摘要、手动长期记忆与角色卡边界
数据库
笃行3504 天前
金仓数据库数据安全双防线:静态存储加密与传输加密实战
数据库
笃行3504 天前
金仓数据库物理备份实战:sys_rman 全流程演练与误覆盖抢救
数据库
笃行3504 天前
金仓数据库逻辑备份实战:从全库导出到 Schema 替换的完整闭环
数据库
SelectDB4 天前
阶跃星辰基于 SelectDB 构建 PB 级 Agent 可观测平台
大数据·数据库·aigc
这个DBA有点耶5 天前
GROUP BY优化全解:如何写出既不丢数据又飞快的分组查询
数据库·mysql·架构