本文介绍了SQL Server错误:ExecuteNonQuery:连接属性尚未初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用ASP.Net和C#开发一个示例注册页面.我正在调用存储过程以将数据插入数据库.我的数据库是SQL Server2008.
I am trying to develop a sample registration page using ASP.Net and C#. I am calling a stored procedure to insert the data to database. My database is SQL Server 2008.
这是我的代码:
public partial class Sample : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
string str;
protected void Page_Load(object sender, EventArgs e)
{
rbt_Male.Checked = true;
}
protected void btn_Submit_Click(object sender, EventArgs e)
{
string @Name = txtbx_Name.Text;
string @Gender_male = rbt_Male.Text;
string @Gender_Female = rbt_Female.Text;
string @Email = txtbx_Email.Text;
DateTime @Dob = Convert.ToDateTime(txt_Dob.Text);
submitdata();
}
protected void submitdata()
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insertdata";
if (rbt_Male.Checked)
{
cmd.Parameters.AddWithValue("@Name", txtbx_Name.Text);
cmd.Parameters.AddWithValue("@Gender_Male", rbt_Male.Text);
cmd.Parameters.AddWithValue("@Email", txtbx_Email.Text);
cmd.Parameters.AddWithValue("@Dob", Convert.ToDateTime(txt_Dob.Text));
}
else if (rbt_Female.Checked)
{
cmd.Parameters.AddWithValue("@Name", txtbx_Name.Text);
cmd.Parameters.AddWithValue("@Gender_Female", rbt_Male.Text);
cmd.Parameters.AddWithValue("@Email", txtbx_Email.Text);
cmd.Parameters.AddWithValue("@Dob", Convert.ToDateTime(txt_Dob.Text));
}
if (con.State == ConnectionState.Closed)
con.Open();
cmd.ExecuteNonQuery();
lbl_Errormsg.Visible = true;
lbl_Errormsg.Text = "Record Inserted Successfully";
con.Close();
}
catch (Exception ex)
{
lbl_Errormsg.Visible = true;
lbl_Errormsg.Text = ex.Message;
}
我收到错误消息
我在 cmd.ExecuteNonQuery();
请帮助我.
我的存储过程是
ALTER Procedure insertdata
(
@Name Varchar(20),
@Gender Varchar(6),
@Email Varchar(20),
@Dob date
)
As
Begin
Insert into samplelogintable (Name, Gender, Email, Dob)
Values(@Name, @Gender, @Email, @Dob)
End
推荐答案
您尚未将命令 cmd
与SqlConnection关联,这就是为什么会出现错误的原因.
You haven't associated your command cmd
with your SqlConnection, that is why you are getting the error.
您需要指定:
cmd.Connection = con;
在您的 submitdata()
方法中.
由于SqlCommand实现 IDisposable ,因此如果使用它在using块之内,例如:
Since SqlCommand implements IDisposable, its better if you use it within using block like:
using (SqlCommand cmd = new SqlCommand())
{
cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insertdata";
cmd.Connection = con;
.... your code
}
这篇关于SQL Server错误:ExecuteNonQuery:连接属性尚未初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!