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

参考:

相关推荐
win x9 分钟前
Redis 使用~如何在Java中连接使用redis
java·数据库·redis
yashuk18 分钟前
C语言实现PAT练习及算法学习笔记,还有SQLite介绍
c语言·sqlite·开源项目·算法学习·pat练习
迷枫7121 小时前
DM8 数据库安装实战:从零搭建达梦数据库环境(附全套工具链接)
数据库
XDHCOM2 小时前
PostgreSQL 25001: active_sql_transaction 报错原因分析,故障修复步骤详解,远程处理解决方案
数据库·sql·postgresql
卤炖阑尾炎2 小时前
PostgreSQL 日常运维全指南:从基础操作到备份恢复
运维·数据库·postgresql
daad7773 小时前
wifi_note
运维·服务器·数据库
xixingzhe23 小时前
Mysql统计空间增量
数据库·mysql
程序员萌萌4 小时前
Redis的缓存机制和淘汰策略详解
数据库·redis·缓存机制·淘汰策略
不剪发的Tony老师5 小时前
SQLite 3.53.0版本发布,重要更新
数据库·sqlite
Bczheng15 小时前
九.Berkeley DB数据库 序列化和钱包管理(1)
数据库