无法连接到 C# 中的本地数据库

Posted

技术标签:

【中文标题】无法连接到 C# 中的本地数据库【英文标题】:Cannot connect to local database in C# 【发布时间】:2011-10-20 18:48:58 【问题描述】:

所以,我有以下代码用于连接记录并将其插入数据库:

string dbfile = "|DataDirectory|\\Databases\\Database.sdf";
            SqlConnection connection = new SqlConnection("Data Source=" + dbfile);
            SqlCommand query = new SqlCommand("insert into Leggers values('" + leggernummer + "','" + omschrijving + "')", connection);
            ** connection.Open(); **
            query.BeginExecuteNonQuery();

            connection.Close();

我的配置文件如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="connectionstring"
            connectionString="Data Source=|DataDirectory|\Databases\Database.sdf"
            providerName="Microsoft.SqlServerCe.Client.3.5" />
    </connectionStrings>
</configuration>

然后在第一个代码块中**和**之间的部分给出错误

错误是:

System.Data.SqlClient.SqlException was unhandled
  Message=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)
  Source=.Net SqlClient Data Provider
  ErrorCode=-2146232060
  Class=20
  LineNumber=0
  Number=-1
  Server=""
  State=0
  StackTrace:
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
       at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity)
       at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject)
       at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout)
       at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
       at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
       at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
       at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
       at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
       at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
       at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
       at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
       at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
       at System.Data.SqlClient.SqlConnection.Open()
       at Stockbeheer_Savenay.Forms.LeggerToevoegen.addItem(String leggernummer, String omschrijving) in C:\Users\Simon\Desktop\Stockbeheer Savenay\Stockbeheer Savenay\Forms\LeggerToevoegen.cs:line 59
       at Stockbeheer_Savenay.Forms.LeggerToevoegen.btnToevoegen_Click(Object sender, EventArgs e) in C:\Users\Simon\Desktop\Stockbeheer Savenay\Stockbeheer Savenay\Forms\LeggerToevoegen.cs:line 31
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at Stockbeheer_Savenay.Program.Main() in C:\Users\Simon\Desktop\Stockbeheer Savenay\Stockbeheer Savenay\Classes\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

我是 C# 数据库的新手,所以我不确定出了什么问题。尝试按照教程进行操作,但它们都说不同的东西,所以很难弄清楚我到底应该做什么。

谢谢!

【问题讨论】:

您可以通过 SQL Server Management Studio 连接到数据库吗?如果是这样,您使用什么信息进行连接,连接后您的数据库是否可见?那 DB 的名字是什么?我想我们只需要在这里调试您的连接字符串... SQLEXPRESS 服务实例是否正在运行? @MerlynMorgan-Graham:我不确定那个 SQL Server Management Studio 是什么。我在 Visual Studio 中创建了数据库,并且连接在那里工作,我已经测试过了。数据库的名称只是“数据库”。 @kprobst:我在我的任务主机(或任何英文名称)中看不到该服务 @kprobst:这是一个 .sdf 文件 = SQL Server Compact Edition 不是 SQL Server Express 【参考方案1】:

使用.sdf 文件(SQL Server 精简版)时,您需要使用SqlCeConnection SqlConnection(适用于完整的SQL服务器):

string dbfile = "|DataDirectory|\\Databases\\Database.sdf";

string insertStmt = "insert into Leggers values('" + leggernummer + "','" + omschrijving + "')";

using(SqlCeConnection connection = new SqlCeConnection("Data Source=" + dbfile))
using(SqlCeCommand query = new SqlCeCommand(insertStmt, connection))

    connection.Open();
    query.BeginExecuteNonQuery();
    connection.Close();

另外:您应该尝试使用参数化查询,而不仅仅是将您的 SQL 语句连接在一起......(研究“SQL 注入攻击”......)

【讨论】:

它无法识别 SqlCeConnection 和 SqlCeCommand。我有以下 using 指令: using System.Data;使用 System.Data.SqlClient;使用 System.Data.OleDb;另外:该程序是一个离线应用程序,只有 1 人将使用。所以我没有 SQL 注入的风险。 好的,现在连接好了。但是,我的数据库没有使用我添加的新记录进行更新。 或者它只是忽略了添加的内容,因为我正在调试? (抱歉发了三次帖子,编辑太晚了) @Simon:仔细查看您的文件夹,您可能有 2 个 .sdf 副本(在源代码和 \bin\debug 中)

以上是关于无法连接到 C# 中的本地数据库的主要内容,如果未能解决你的问题,请参考以下文章

无法在本地环境中使用 docker 连接到 cakephp 中的 mysql 数据库

无法使用 JDBC 连接到 docker 中的本地 MySQL

如何从 Docker-Compose C# 应用程序连接到本地 SQL Server Express 数据库?

启用 SSL 的网站无法连接到本地 C# Web 套接字服务器

Android设备无法连接到本地主机中的mysql [关闭]

我无法使用 DataGrip 数据库客户端从本地主机连接到 docker 中的 mysql