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();
    }
}

参考:

相关推荐
百结2142 小时前
Mysql数据库操作
数据库·mysql·oracle
keep one's resolveY2 小时前
时区问题解决
数据库
Leinwin2 小时前
OpenClaw 多 Agent 协作框架的并发限制与企业化规避方案痛点直击
java·运维·数据库
qq_417695052 小时前
机器学习与人工智能
jvm·数据库·python
漫随流水2 小时前
旅游推荐系统(view.py)
前端·数据库·python·旅游
ego.iblacat3 小时前
MySQL 服务基础
数据库·mysql
Maverick064 小时前
Oracle Redo 日志操作手册
数据库·oracle
攒了一袋星辰5 小时前
高并发强一致性顺序号生成系统 -- SequenceGenerator
java·数据库·mysql
W.D.小糊涂5 小时前
gpu服务器安装windows+ubuntu24.04双系统
c语言·开发语言·数据库
云贝教育-郑老师5 小时前
【OceanBase 的多租户架构是怎样的?有什么优势?】
数据库·oceanbase