【问题标题】:Troubleshoot my connection string problems解决我的连接字符串问题
【发布时间】:2013-03-13 19:56:48
【问题描述】:

我正在尝试制作简单的注册表单,我想将文本框中的数据插入 DataSet 这里的表格是我的 WebForm 代码:​​

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
using System.Configuration;
using System.Data.SqlClient;


namespace IknowyourbrainWebSite
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);


        protected void Page_Load(object sender, EventArgs e)
        {
            con.Open();
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand("insert into tbl values('"+TxtUserName.Text+"','"+TxtPassword.Text+"','"+TxtRePassword.Text+"')", con);
            cmd.ExecuteNonQuery();
            con.Close();
            TxtUserName.Text = "";
            TxtPassword.Text = "";
            TxtRePassword.Text = "";


        }
    }
}

当我启动它时出现错误:

Server Error in '/' Application.
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) 
 Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

 Exception Details: System.Data.SqlClient.SqlException: 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 Error: 

Line 20:         protected void Page_Load(object sender, EventArgs e)
Line 21:         {
Line 22:             con.Open();
Line 23:         }
Line 24: 


 Source File:  c:\Users\Fluksikarton\Documents\Visual Studio 2012\Projects\IknowyourbrainWebSite\IknowyourbrainWebSite\WebForm1.aspx.cs    Line:  22 

Stack Trace: 

[SqlException (0x80131904): 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)]
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5295167
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +242
   System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +5307115
   System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +145
   System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +920
   System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +307
   System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions) +434
   System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +225
   System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +37
   System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions userOptions) +558
   System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOptions userOptions) +67
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1052
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +78
   System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +167
   System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +143
   System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +83
   System.Data.SqlClient.SqlConnection.Open() +96
   IknowyourbrainWebSite.WebForm1.Page_Load(Object sender, EventArgs e) in c:\Users\Fluksikarton\Documents\Visual Studio 2012\Projects\IknowyourbrainWebSite\IknowyourbrainWebSite\WebForm1.aspx.cs:22
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnLoad(EventArgs e) +92
   System.Web.UI.Control.LoadRecursive() +54
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
enter code here

这个错误是否有可能是由于我的公共 IP 不是静态的,我的意思是动态的,据我所知,每次我重新启动路由器或调制解调器时它都会改变,或者问题出在我的代码中/选项

这是我在 web.config 中的连接字符串代码:

<configuration>
    <connectionStrings>
        <add name="ConnectionString" connectionString="Data Source=|DataDirectory|\RegistrationDataBase.sdf"
            providerName="System.Data.SqlServerCe.4.0" />
    </connectionStrings>
    <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>


</configuration>

【问题讨论】:

  • 警告您的代码容易受到 sql 注入攻击。
  • 检查您的连接字符串。
  • 仅在需要时打开连接(即在使用前)
  • ...正如例外所说。
  • 如果不查看 web.config 中的连接字符串,就很难判断问题所在。一般来说,请确保您指向正确的实例、数据库名称等。确保您的 SQL Server 可以访问 Web 服务器或 IIS,或者如果它们位于同一个框上,您可以使用 localhost。

标签: c# asp.net


【解决方案1】:

如果您的连接字符串设置不正确,通常会触发此错误。您是否验证过它是正确的,服务器名称和实例是否正确,凭据是否正确以及您的服务器是否设置为接收远程连接(假设它与您的代码不在同一个盒子上)?

【讨论】:

  • 我不知道你真正要我做什么,你能指导我吗?对不起,我是这个 SQL 连接的新手
  • @Boris,你能发布你的连接字符串吗?您可以在项目根目录下的 App.config 或 Web.config 文件中的 &lt;connectionStrings&gt; 部分中找到它
  • @Boris,好的,您的应用程序的 App_Data 文件夹中是否存在“RegistrationDatabase.sdf”文件?
  • y 在我的 App_Data 文件夹中我有 RegistratonDataBase.sdf 文件
【解决方案2】:

错误通常是错误的连接字符串。请检查一下。

你为什么不这样重写Button2_Click。

protected void Button2_Click(object sender, EventArgs e)
{
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand("insert into tbl values('"+TxtUserName.Text+"','" + TxtPassword.Text+"','"+TxtRePassword.Text+"')", con);
        cmd.ExecuteNonQuery();
        con.Close();
        TxtUserName.Text = "";
        TxtPassword.Text = "";
        TxtRePassword.Text = "";

}

一些不错的起点:

How to check if connection string is valid?

http://www.connectionstrings.com/

阅读您遇到的实际错误

[SqlException (0x80131904): 网络相关或实例特定 建立与 SQL Server 的连接时出错。这 服务器未找到或无法访问。验证实例 名称正确且 SQL Server 配置为允许远程 连接。 (提供者:SQL 网络接口,错误:26 - 错误 定位服务器/指定实例)]

【讨论】:

  • 所以我不是在 load_page 中打开 con.open,而是在按钮中打开它,点击很好,我试试
  • 同样的事情发生了,但是当我打开页面时,当我点击按钮时会立即发生
  • 您的连接字符串是我认为的真正问题。
  • 向我们展示您的真实连接字符串 - 删除密码 :-)
  • using (var con = new ...), using (var cmd = new ...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 2011-09-20
  • 2016-01-20
相关资源
最近更新 更多