【发布时间】:2020-02-17 21:41:19
【问题描述】:
当我启动我的应用程序时,我收到此错误:
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=\"Web\" /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,但您没有告诉这个对象要使用的连接字符串是什么。