簡體   English   中英

修復 ConnectionString 屬性尚未初始化

[英]fix The ConnectionString property has not been initialized

當我啟動我的應用程序時,我收到此錯誤:

ConnectionString 屬性尚未初始化。

嘗試連接到我的 SQL Server 數據庫時出現此異常。

注冊.aspx.cs

protected void btnRegister_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection();

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;
    cmd.CommandText = string.Format("insert into member 
values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')",
            txtFullName.Text, rblGender.SelectedValue, ddlCountry.SelectedValue,
            txtPhone.Text, txtEmail.Text, txtUsername.Text, txtPassword.Text);

    try
    {
        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();

        tblRegister.Visible = false;
        Response.Write("Your account is created.");
    }
    catch(SqlException ex)
    {
        if (ex.Number == 2627)
            lblMsg.Text = "Please Change The Username.";
        else
            lblMsg.Text = "An Error : " + ex.Message; 
    }
}

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.6.1"/>
        <httpRuntime targetFramework="4.6.1"/>
    </system.web>
    <system.codedom>
        <compilers>
            <compiler language="c#;cs;csharp" extension=".cs"
                      type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, 
Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                      warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
            <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
                      type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, 
Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                      warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
        </compilers>
    </system.codedom>
    <appSettings>
        <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
    </appSettings>
    <connectionStrings>
        <add name="MyDB"
             connectionString="Data Source=.\sqlexpress;Initial Catalog=Company;Integrated Security=True"
             providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

你需要這樣做:

SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=MSSQL1;Initial Catalog=AdventureWorks;Integrated Security=true;"";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;

使用 ConnectionString,您可以指定要連接到的服務器以及使用什么憑據,否則它將不知道您要連接到的位置和連接的內容。 我給出的示例是針對 SQL 服務器和集成安全性的,根據您的數據庫、服務器和憑據,您需要找到所需的連接字符串

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM