c#写一个sqlite数据库
时间: 2023-08-02 13:25:09 浏览: 55
首先,你需要安装SQLite数据库并引用System.Data.SQLite命名空间。然后,你可以按照以下步骤编写C#代码来创建和操作SQLite数据库:
1. 创建数据库连接对象并打开连接:
```csharp
using System.Data.SQLite;
string connectionString = "Data Source=yourDatabase.db;Version=3;";
SQLiteConnection connection = new SQLiteConnection(connectionString);
connection.Open();
```
2. 创建表:
```csharp
string createTableQuery = @"CREATE TABLE IF NOT EXISTS MyTable (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Name TEXT NOT NULL,
Age INTEGER NOT NULL)";
SQLiteCommand command = new SQLiteCommand(createTableQuery, connection);
command.ExecuteNonQuery();
```
3. 插入数据:
```csharp
string insertQuery = "INSERT INTO MyTable (Name, Age) VALUES ('John', 30)";
SQLiteCommand command = new SQLiteCommand(insertQuery, connection);
command.ExecuteNonQuery();
```
4. 查询数据:
```csharp
string selectQuery = "SELECT * FROM MyTable";
SQLiteCommand command = new SQLiteCommand(selectQuery, connection);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32(0);
string name = reader.GetString(1);
int age = reader.GetInt32(2);
Console.WriteLine($"Id: {id}, Name: {name}, Age: {age}");
}
```
5. 关闭连接:
```csharp
connection.Close();
```
这样,你就可以使用C#来创建和操作SQLite数据库了。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)