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

c# sqlite

作者:戮尽逆者   发布日期:2025-04-29   浏览:105

using System;
using System.Data.SQLite;

class Program
{
    static void Main()
    {
        // 创建一个新的数据库连接
        string connectionString = "Data Source=example.db;Version=3;";
        using (SQLiteConnection connection = new SQLiteConnection(connectionString))
        {
            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 ('Alice', 30), ('Bob', 25)";
                using (SQLiteCommand command = new SQLiteCommand(insertQuery, connection))
                {
                    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. 打开数据库连接:使用 Open() 方法打开数据库连接。
  3. 创建表:使用 CREATE TABLE IF NOT EXISTS SQL 语句创建一个名为 Users 的表,包含 Id, Name, 和 Age 列。
  4. 插入数据:使用 INSERT INTO SQL 语句向 Users 表中插入两条记录。
  5. 查询数据:使用 SELECT SQL 语句从 Users 表中查询所有记录,并使用 SQLiteDataReader 来读取查询结果。
  6. 异常处理:使用 try-catch-finally 块来捕获并处理可能发生的异常,并确保在任何情况下都关闭数据库连接。

上一篇:c# 正则表达式

下一篇:c# 随机数

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# if else

c#高并发

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

Laravel 中文站