VS2015中C# Web Forms应用连接SQLite数据库的方法咨询
在VS2015的C# Web Forms中访问SQLite数据库的解决方案
1. 所需NuGet包及安装步骤
- 安装System.Data.SQLite(版本1.0.116,和你WinForm项目使用的版本一致):
- 打开VS2015的NuGet包管理器控制台(路径:工具 → NuGet包管理器 → 包管理器控制台)
- 在控制台中执行命令:
Install-Package System.Data.SQLite -Version 1.0.116
- 说明:这个包会自动安装依赖的
SQLite.Core等组件,安装完成后项目引用列表会自动添加System.Data.SQLite相关条目,无需手动添加引用。
2. Web.config配置
连接字符串配置
在Web.config的<configuration>节点内添加<connectionStrings>节点:
<connectionStrings> <add name="SQLiteConnection" connectionString="Data Source=|DataDirectory|\DB.sqlite;Version=3;" providerName="System.Data.SQLite" /> </connectionStrings>
|DataDirectory|是Web Forms的特殊路径占位符,会自动映射到项目的App_Data文件夹,建议将DB.sqlite文件放在该目录下,避免文件权限问题。
数据库提供程序配置(可选)
如果出现驱动无法识别的情况,在<configuration>节点下添加<system.data>配置:
<system.data> <DbProviderFactories> <remove invariant="System.Data.SQLite" /> <add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" /> </DbProviderFactories> </system.data>
3. 后端访问示例代码
以下是一个简单的数据查询示例,可放在Web Forms页面的后台代码文件(如Default.aspx.cs)中:
using System; using System.Data; using System.Data.SQLite; using System.Configuration; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // 从Web.config读取连接字符串 string connectionString = ConfigurationManager.ConnectionStrings["SQLiteConnection"].ConnectionString; // 使用using块自动管理连接生命周期 using (SQLiteConnection conn = new SQLiteConnection(connectionString)) { try { conn.Open(); // 替换为你实际的查询SQL string querySql = "SELECT Id, Name FROM YourTableName"; using (SQLiteCommand cmd = new SQLiteCommand(querySql, conn)) { using (SQLiteDataReader reader = cmd.ExecuteReader()) { // 遍历查询结果 while (reader.Read()) { // 读取列值,可根据实际列名调整 int id = reader.GetInt32(reader.GetOrdinal("Id")); string name = reader.GetString(reader.GetOrdinal("Name")); // 将结果输出到页面(示例) Response.Write($"ID: {id}, 名称: {name}<br/>"); } } } } catch (Exception ex) { Response.Write($"数据库访问出错: {ex.Message}"); } } } }
- 注意事项:
- 将
YourTableName替换为数据库中实际的表名; - 建议将数据库操作封装到独立的类库或工具类中,便于代码复用和维护;
- 本地调试时若遇到文件权限问题,可右键
App_Data文件夹→属性→安全→添加IIS_IUSRS用户并赋予读写权限。
- 将
内容的提问来源于stack exchange,提问作者CSH
相关产品推荐
相关产品推荐

