Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

sqlite c#

作者:﹏尐甶园   发布日期:2026-04-01   浏览:110

using System;
using System.Data.SQLite;

class Program
{
    static void Main()
    {
        // 创建一个新的 SQLite 数据库连接
        using (SQLiteConnection connection = new SQLiteConnection("Data Source=mydatabase.db;Version=3;"))
        {
            try
            {
                // 打开数据库连接
                connection.Open();
                Console.WriteLine("数据库连接成功");

                // 创建一个表
                string createTableQuery = "CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY, Name TEXT, Age INTEGER)";
                using (SQLiteCommand command = new SQLiteCommand(createTableQuery, connection))
                {
                    command.ExecuteNonQuery();
                    Console.WriteLine("表创建成功");
                }

                // 插入数据
                string insertQuery = "INSERT INTO Users (Name, Age) VALUES (@Name, @Age)";
                using (SQLiteCommand command = new SQLiteCommand(insertQuery, connection))
                {
                    command.Parameters.AddWithValue("@Name", "John Doe");
                    command.Parameters.AddWithValue("@Age", 30);
                    command.ExecuteNonQuery();
                    Console.WriteLine("数据插入成功");
                }

                // 查询数据
                string selectQuery = "SELECT * FROM Users";
                using (SQLiteCommand command = new SQLiteCommand(selectQuery, connection))
                {
                    using (SQLiteDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            Console.WriteLine($"ID: {reader["Id"]}, Name: {reader["Name"]}, Age: {reader["Age"]}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
            }
            finally
            {
                // 关闭数据库连接
                connection.Close();
                Console.WriteLine("数据库连接已关闭");
            }
        }
    }
}

解释说明:

  1. 创建数据库连接:使用 SQLiteConnection 类创建一个新的数据库连接,并指定数据库文件路径和版本。
  2. 打开连接:通过 connection.Open() 方法打开数据库连接。
  3. 创建表:使用 CREATE TABLE SQL 语句创建一个名为 Users 的表,包含 Id, Name, 和 Age 列。
  4. 插入数据:使用 INSERT INTO SQL 语句向 Users 表中插入一条记录。为了防止 SQL 注入攻击,使用参数化查询。
  5. 查询数据:使用 SELECT SQL 语句从 Users 表中读取所有记录,并通过 SQLiteDataReader 类遍历结果集。
  6. 异常处理:使用 try-catch-finally 块来捕获并处理可能发生的异常,确保在任何情况下都能正确关闭数据库连接。

希望这段代码和解释对你有帮助!

上一篇:c# list转string

下一篇:c#连接oracle数据库

大家都在看

c# 二进制

c# 创建目录

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站