0

我正在尝试制作简单的注册表单,我想将文本框中的数据插入到 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>
4

2 回答 2

0

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

于 2013-03-13T19:59:13.790 回答
0

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

你为什么不像这样重写 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 = "";

}

一些好的起点:

如何检查连接字符串是否有效?

或者

http://www.connectionstrings.com/

阅读你得到的实际错误

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

于 2013-03-13T20:01:31.840 回答