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

参考:

相关推荐
Dxy123931021610 分钟前
MySQL如何高效查询表数据量:从基础到进阶的优化指南
数据库·mysql
Dying.Light13 分钟前
MySQL相关问题
数据库·mysql
蜡笔小炘1 小时前
LVS -- 利用防火墙标签(FireWall Mark)解决轮询错误
服务器·数据库·lvs
韩立学长1 小时前
基于Springboot泉州旅游攻略平台d5h5zz02(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·旅游
Re.不晚1 小时前
MySQL进阶之战——索引、事务与锁、高可用架构的三重奏
数据库·mysql·架构
老邓计算机毕设2 小时前
SSM智慧社区信息化服务平台4v5hv(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面
数据库·ssm 框架·智慧社区、·信息化平台
麦聪聊数据2 小时前
为何通用堡垒机无法在数据库运维中实现精准风控?
数据库·sql·安全·低代码·架构
2301_790300962 小时前
Python数据库操作:SQLAlchemy ORM指南
jvm·数据库·python
m0_736919102 小时前
用Pandas处理时间序列数据(Time Series)
jvm·数据库·python
亓才孓2 小时前
[JDBC]PreparedStatement替代Statement
java·数据库