c#+sqlite增删改查
时间: 2023-11-12 17:05:27 浏览: 174
在C#中使用SQLite进行增删改查操作,可以使用SQLite.NET库。以下是一个简单的示例代码:
1. 引用SQLite.NET库
```csharp
using System.Data.SQLite;
```
2. 创建数据库连接
```csharp
string connectionString = "Data Source=myDatabase.sqlite;Version=3;";
SQLiteConnection connection = new SQLiteConnection(connectionString);
```
3. 打开数据库连接
```csharp
connection.Open();
```
4. 执行SQL语句进行增删改查操作
```csharp
// 插入数据
string insertSql = "INSERT INTO myTable (name, age) VALUES ('Tom', 20)";
SQLiteCommand insertCommand = new SQLiteCommand(insertSql, connection);
insertCommand.ExecuteNonQuery();
// 更新数据
string updateSql = "UPDATE myTable SET age = 21 WHERE name = 'Tom'";
SQLiteCommand updateCommand = new SQLiteCommand(updateSql, connection);
updateCommand.ExecuteNonQuery();
// 删除数据
string deleteSql = "DELETE FROM myTable WHERE name = 'Tom'";
SQLiteCommand deleteCommand = new SQLiteCommand(deleteSql, connection);
deleteCommand.ExecuteNonQuery();
// 查询数据
string selectSql = "SELECT * FROM myTable";
SQLiteCommand selectCommand = new SQLiteCommand(selectSql, connection);
SQLiteDataReader reader = selectCommand.ExecuteReader();
while (reader.Read())
{
string name = reader.GetString(0);
int age = reader.GetInt32(1);
Console.WriteLine("Name: {0}, Age: {1}", name, age);
}
```
5. 关闭数据库连接
```csharp
connection.Close();
```
阅读全文