C# 连接SQLite数据库与建表

102 阅读1分钟

SQLite 是⼀个软件库, 实现了自给自足的 、无服务器的 、零配置的 、事务性的 轻量级SQL 数据库引 擎。

  1. 声明连接SQLite的变量Conn 添加SQLite操作驱动dll引用:System.Data.SQLite.dll
using System.Data.SQLite; 

SQLiteConnection Conn;

直接NuGet包搜索 System.Data.SQLite.Core

image.png

  1. 创建⼀个连接到指定数据库 判断是否存在该文件,不存在则在该路径创建, 然后连接数据库
string FilePath = Application.StartupPath + "\\transfer.db";
if ( !File.Exists(FilePath))

SQLiteConnection.CreateFile(FilePath);
}
try

Conn = new SQLiteConnection("Data Source=" + FilePath + ";Version=3;"
);
Conn.Open();
}
catch (Exception ex)
throw new Exception("打开数据库:" + FilePath + "的连接失败: " + ex.Messag e);
}

3. 创建table

string sql = "create table info (name varchar(20), address varchar(40))";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

作者:邬宏涛