C#连接sqlite3数据库
时间: 2023-06-19 08:10:18 浏览: 79
连接 SQLite3 数据库可以使用 System.Data.SQLite 这个第三方库。以下是连接 SQLite3 数据库的步骤:
1. 下载 System.Data.SQLite 库并将其添加到你的项目中。
2. 引入命名空间:`using System.Data.SQLite;`
3. 创建连接字符串,指定 SQLite 数据库文件的路径和名称。
```
string connectionString = @"Data Source=C:\sqlite\db\test.db;";
```
4. 创建 SQLiteConnection 对象并打开连接。
```
SQLiteConnection connection = new SQLiteConnection(connectionString);
connection.Open();
```
5. 执行 SQL 命令,例如创建表、插入数据等。
```
string createTable = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)";
SQLiteCommand command = new SQLiteCommand(createTable, connection);
command.ExecuteNonQuery();
```
6. 关闭连接。
```
connection.Close();
```
完整示例代码:
```
using System;
using System.Data.SQLite;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string connectionString = @"Data Source=C:\sqlite\db\test.db;";
SQLiteConnection connection = new SQLiteConnection(connectionString);
connection.Open();
string createTable = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)";
SQLiteCommand command = new SQLiteCommand(createTable, connection);
command.ExecuteNonQuery();
connection.Close();
}
}
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)