如何使用 C# 访问 SQLite?

2024-04-20

我正在尝试使用 C#/ASP.NET 以编程方式连接到我的 Sqlite 数据库:

string requete_sql = "SELECT * FROM USERS";
connStr = @"Data Source=C:\LocalFolder\FooBar.db;";
using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr)) {
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(requete_sql,conn);
conn.Open();
cmd.ExecuteNonQuery();
}

但是出现了一个异常(在 conn.Open() 行上),告诉我们:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

这很奇怪,因为我复制了 Web.config 文件中找到的确切连接字符串。

我怎样才能避免这个异常?

PS:我的目标是仅以编程方式连接到数据库,而无需 web.config 文件。

谢谢你,

Regards.


C# 中的 SQLite(需要System.Data.SQLite参考文献中)

// Required references, after installing SQLite via Nuget
using System.Data.SQLite;
using System.Data.Common;

// Example usage in code...
SQLiteConnection db = new SQLiteConnection("Data Source=C:\LocalFolder\FooBar.db;FailIfMissing=True;");
db.Open();
using (SQLiteCommand comm=db.CreateCommand()) {
  comm.CommandText = requete_sql;
  IDataReader dr=comm.ExecuteReader();
  while (dr.Read())
  {
    //...
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 C# 访问 SQLite? 的相关文章

随机推荐