【问题标题】:How can I access SQLite with C#?如何使用 C# 访问 SQLite?
【发布时间】:2019-05-31 02:07:23
【问题描述】:

我正在尝试使用 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 文件。

谢谢,

问候。

【问题讨论】:

    标签: c# sqlite connection-string


    【解决方案1】:

    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())
      {
        //...
      }
    }
    

    【讨论】:

    • 也许应该提一下,这不仅仅是一个参考,而是一个 NuGet 依赖。
    【解决方案2】:

    您无法使用 SQLProvider 类连接到 sqlite db。它们适用于 sql server。您需要使用SQLite provider 类。

    【讨论】:

    【解决方案3】:

    MSDN 杂志上有一篇关于此的文章:

    http://msdn.microsoft.com/en-us/magazine/ff898405.aspx

    【讨论】:

      【解决方案4】:
      1. http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki
      2. 在您的项目中引用 System.Data.SQLite.DLL(这将为您提供 SQLiteConnection 类)
      3. 联系

        SQLiteConnection connection = new SQLiteConnection(@"DbLinqProvider=Sqlite;Data Source=Database.s3db"); 
        Main main = new Main(connection);
        

      详情请见https://code.google.com/p/dblinq2007/wiki/Installation#To_use_DbLinq

      【讨论】:

        猜你喜欢
        • 2011-10-01
        • 2021-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-08
        • 2012-03-16
        • 2023-03-24
        • 1970-01-01
        相关资源
        最近更新 更多