如何将记录插入SQLServer 2008数据库?
我在将注册 Web 表单中的数据插入 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 中吗?请帮忙!非常感谢任何帮助。
I'm having trouble inserting data from my registration webform into sqlserver-2008. I'm getting an error in VS: The connection was not closed. The connection's current state is open.
Here's the code that I have:
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();
}
Any idea why it is not inserting into the SQL Server? Please help! Any help is much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我看来,您正在第二次打开 objCon 。您的
if
确保它已打开,然后在分配 sql 字符串后尝试再次打开它。您有这种情况:
然后,在这种情况下您说
objCon.Open();
消除有问题的
objCon.Open();
It looks to me like you're opening
objCon
a second time. Yourif
makes sure it's open, then you try to open it again after you assign the sql string.You have this condition:
then, within that condition you say
objCon.Open();
Eliminate that problematic
objCon.Open();