gpt4 book ai didi

c# - SQL 服务器错误 : ExecuteNonQuery: Connection property has not been initialized

转载 作者:太空宇宙 更新时间:2023-11-03 20:19:18 26 4
gpt4 key购买 nike

我正在尝试使用 ASP.Net 和 C# 开发示例注册页面。我正在调用存储过程将数据插入数据库。我的数据库是 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;
}

我收到错误信息

ExecuteNonQuery: Connection property has not been initialized.

我在 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 相关联,这就是您收到错误的原因。

您需要指定:

cmd.Connection = con;

在您的 submitdata() 方法中。

由于 SqlCommand 实现了 IDisposable ,如果你在 using block 中使用它会更好,比如:

using (SqlCommand cmd = new SqlCommand())
{

cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insertdata";
cmd.Connection = con;
.... your code

}

关于c# - SQL 服务器错误 : ExecuteNonQuery: Connection property has not been initialized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14618941/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com