我真的不知道为什么我收到这条消息
ExecuteNonQuery:CommandText属性尚未初始化
我的代码中没有任何错误,当我看到它时看起来很好。我一直在寻找网络寻求解决方案,但找不到任何解决方案。这是我的代码。任何帮助非常感谢。
SqlConnection conn = new SqlConnection("Data Source=VALONS;Initial Catalog=gym;Integrated Security=True");
SqlCommand cmd;
public NewMem()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
}
private void NewMem_Load(object sender, EventArgs e)
{
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
conn.Open();
cmd = new SqlCommand("Insert into member(SocialSecurity, Name, City, Street, Zipcode, Email, Phone) values ('" + textSocialSecurity + "','" + textName + "','" + textCity + "','" + textStreet + "','" + textZipCode + "','" + textEmail + "','" + textPhone + "')" + conn);
cmd.ExecuteNonQuery();
MessageBox.Show("You have successfully inserted values in Member");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
答案 0 :(得分:0)
该问题可能与datataype不匹配有关。 尝试使用参数而不是直接值,因为sql注入问题。
cmd = new SqlCommand("Insert into member(SocialSecurity, Name, City, Street, Zipcode, Email, Phone) values (:1,:2,:3,:4,:5,:6,:7)", conn);
cmd.parameters.clear();
cmd.parameters.Add("1", textSocialSecurity);
cmd.parameters.Add("2", textName);
...
cmd.parameters.Add("7", textPhone);
cmd.ExecuteNonQuery();
答案 1 :(得分:0)
你可能必须这样做:
cmd.CommandText = @"Insert into member(SocialSecurity, Name, City, Street, Zipcode, Email, Phone) values ('" + textSocialSecurity + "','" + textName + "','" + textCity + "','" + textStreet + "','" + textZipCode + "','" + textEmail + "','" + textPhone + "')";
但是你有严重的问题。你可以接受sql注射。
参数化查询。
答案 2 :(得分:-1)
您的命令需要被告知它是什么类型。存储过程,命令文本等我不记得方法,但这就是问题。
我建议您分阶段执行此操作 - 打开连接,创建命令对象并设置连接属性,设置其类型并执行SQL文本。我还建议使用带参数的存储过程来解决SQL注入问题。