本文将详细介绍如何使用 C# 在 SQLite 数据库中执行 INSERT 操作。INSERT 操作是数据库管理中最基本和常用的操作之一,用于向表中添加新的数据记录。
首先,确保你的项目中已安装 System.Data.SQLite
NuGet 包。在你的 C# 文件顶部添加以下 using 语句:
C#using System;
using System.Data.SQLite;
在执行任何数据库操作之前,我们需要建立与数据库的连接。以下是一个建立连接的辅助方法:
C#public static SQLiteConnection ConnectToDatabase(string dbPath)
{
try
{
SQLiteConnection connection = new SQLiteConnection($"Data Source={dbPath};Version=3;");
connection.Open();
return connection;
}
catch (Exception ex)
{
Console.WriteLine($"连接数据库时出错:{ex.Message}");
return null;
}
}
C#public static void CreateTable(SQLiteConnection connection, string tableName, string[] columns)
{
try
{
string columnsDefinition = string.Join(", ", columns);
string sql = $"CREATE TABLE IF NOT EXISTS {tableName} ({columnsDefinition})";
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
command.ExecuteNonQuery();
}
Console.WriteLine($"表 {tableName} 创建成功。");
}
catch (Exception ex)
{
Console.WriteLine($"创建表时出错:{ex.Message}");
}
}
SQLstring[] columns = {
"ID INTEGER PRIMARY KEY AUTOINCREMENT",
"Name TEXT NOT NULL",
"Age INTEGER",
"Email TEXT"
};
CreateTable(connection, "Users", columns);
以下是一个基本的插入单条记录的方法:
C#public static void InsertRecord(SQLiteConnection connection, string tableName, Dictionary<string, object> data)
{
try
{
string columns = string.Join(", ", data.Keys);
string values = string.Join(", ", data.Keys.Select(k => "@" + k));
string sql = $"INSERT INTO {tableName} ({columns}) VALUES ({values})";
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
foreach (var item in data)
{
command.Parameters.AddWithValue("@" + item.Key, item.Value);
}
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine($"成功插入 {rowsAffected} 条记录。");
}
}
catch (Exception ex)
{
Console.WriteLine($"插入记录时出错:{ex.Message}");
}
}
使用示例:
C#var data = new Dictionary<string, object>
{
{ "Name", "John Doe" },
{ "Age", 30 },
{ "Email", "john@example.com" }
};
InsertRecord(connection, "Users", data);
对于需要插入多条记录的情况,我们可以使用事务来提高性能:
C#public static void InsertMultipleRecords(SQLiteConnection connection, string tableName, List<Dictionary<string, object>> dataList)
{
try
{
using (SQLiteTransaction transaction = connection.BeginTransaction())
{
foreach (var data in dataList)
{
string columns = string.Join(", ", data.Keys);
string values = string.Join(", ", data.Keys.Select(k => "@" + k));
string sql = $"INSERT INTO {tableName} ({columns}) VALUES ({values})";
using (SQLiteCommand command = new SQLiteCommand(sql, connection, transaction))
{
foreach (var item in data)
{
command.Parameters.AddWithValue("@" + item.Key, item.Value);
}
command.ExecuteNonQuery();
}
}
transaction.Commit();
Console.WriteLine($"成功插入 {dataList.Count} 条记录。");
}
}
catch (Exception ex)
{
Console.WriteLine($"插入多条记录时出错:{ex.Message}");
}
}
使用示例:
C#var dataList = new List<Dictionary<string, object>>
{
new Dictionary<string, object> { { "Name", "Alice" }, { "Age", 25 }, { "Email", "alice@example.com" } },
new Dictionary<string, object> { { "Name", "Bob" }, { "Age", 35 }, { "Email", "bob@example.com" } },
new Dictionary<string, object> { { "Name", "Charlie" }, { "Age", 40 }, { "Email", "charlie@example.com" } }
};
InsertMultipleRecords(connection, "Users", dataList);
如果你的表有一个自增的主键,你可能想在插入后获取这个 ID。以下是一个实现这个功能的方法:
C#public static long InsertRecordAndGetId(SQLiteConnection connection, string tableName, Dictionary<string, object> data)
{
try
{
string columns = string.Join(", ", data.Keys);
string values = string.Join(", ", data.Keys.Select(k => "@" + k));
string sql = $"INSERT INTO {tableName} ({columns}) VALUES ({values}); SELECT last_insert_rowid();";
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
foreach (var item in data)
{
command.Parameters.AddWithValue("@" + item.Key, item.Value);
}
long newId = (long)command.ExecuteScalar();
Console.WriteLine($"成功插入记录,新 ID 为:{newId}");
return newId;
}
}
catch (Exception ex)
{
Console.WriteLine($"插入记录并获取 ID 时出错:{ex.Message}");
return -1;
}
}
使用示例:
C#var data = new Dictionary<string, object>
{
{ "Name", "David" },
{ "Age", 28 },
{ "Email", "david@example.com" }
};
long newId = InsertRecordAndGetId(connection, "Users", data);
注意,在上述所有方法中,我们都使用了参数化查询。这是一个很好的做法,因为:
以下是一个完整的示例,展示了如何使用上述所有方法:
C#using System;
using System.Collections.Generic;
using System.Data.SQLite;
class Program
{
static void Main(string[] args)
{
string dbPath = "C:\\example.db";
SQLiteConnection connection = ConnectToDatabase(dbPath);
if (connection != null)
{
// 插入单条记录
var singleData = new Dictionary<string, object>
{
{ "Name", "John Doe" },
{ "Age", 30 },
{ "Email", "john@example.com" }
};
InsertRecord(connection, "Users", singleData);
// 插入多条记录
var multipleData = new List<Dictionary<string, object>>
{
new Dictionary<string, object> { { "Name", "Alice" }, { "Age", 25 }, { "Email", "alice@example.com" } },
new Dictionary<string, object> { { "Name", "Bob" }, { "Age", 35 }, { "Email", "bob@example.com" } }
};
InsertMultipleRecords(connection, "Users", multipleData);
// 插入并获取自增 ID
var dataForId = new Dictionary<string, object>
{
{ "Name", "David" },
{ "Age", 28 },
{ "Email", "david@example.com" }
};
long newId = InsertRecordAndGetId(connection, "Users", dataForId);
// 关闭连接
connection.Close();
}
}
// 在这里实现 ConnectToDatabase, InsertRecord, InsertMultipleRecords, 和 InsertRecordAndGetId 方法
}
本文详细介绍了如何使用 C# 在 SQLite 数据库中执行 INSERT 操作,包括插入单条记录、插入多条记录以及插入并获取自增 ID。这些操作是数据库编程的基础,掌握它们将帮助你更有效地管理和操作数据。
记住,良好的错误处理和安全实践(如使用参数化查询)对于构建健壮和安全的数据库应用程序至关重要。希望这个指南能够帮助你更好地理解和使用 SQLite 数据库的 INSERT 操作!
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!