我在将注册网络表单中的数据插入sqlserver-2008时遇到问题。我在VS中收到错误:连接未关闭。连接的当前状态是打开的。
这是我的代码:
protected void buttonRegister(object sender, EventArgs e)
{
SqlConnection objCon = new SqlConnection(strCon);
try
{
objCon.ConnectionString = strCon;
objCon.Open();
}
catch (Exception ex)
{
this.lblConnect.Text = "Unable to connect to database.";
}
if (objCon.State == System.Data.ConnectionState.Open)
{
Session["users"] = this.txtUsername.Text;
Session["pwd"] = this.txtPassword.Text;
lblConnect.Text = "Connected";
string sql = @"INSERT INTO user (firstname, middlename, lastname, username, email, password) VALUES ('" + txtFirstname.Text
+ "' , '" + txtMiddlename.Text + "', '" + txtLastname.Text + "', '" + txtUsername.Text + "', '" + txtEmailAddr.Text
+ "', '" + txtPassword.Text + "')";
objCon.Open();
SqlCommand cmd = new SqlCommand(sql, objCon);
cmd.ExecuteNonQuery();
SqlDataReader rd = cmd.ExecuteReader();
objCon.Close();
objCon.Dispose();
}
else
{
lblConnect.Text = "Unable to connect to database.";
objCon.Close();
objCon.Dispose();
}
objCon.Close();
objCon.Dispose();
}
知道它为什么不插入SQL Server?请帮忙!非常感谢任何帮助。
答案 0 :(得分:0)
在我看来你第二次打开objCon
。您的if
确保它已打开,然后在分配sql字符串后尝试再次打开它。
你有这个条件:
if (objCon.State == System.Data.ConnectionState.Open)
然后,在这种情况下你会说objCon.Open();
消除有问题的objCon.Open();