首页 > 解决方案 > 收到错误(System.InvalidOperationException:'ExecuteNonQuery:连接属性尚未初始化。')

问题描述

这是我的代码:

private void btnRegister_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=register;Integrated Security=True"); //datasource 
            
    SqlCommand cmd = new SqlCommand(@"INSERT INTO [dbo].[register]
           ([firstname], [lastname], [address], [gender], [email], [phone], [username], [password])
                                      VALUES ('" + txtFname.Text + "', '" + txtLname.Text + "', '" + txtAdd.Text + "', '" + cmbGender.SelectedItem.ToString() + "', '" + txtEmail.Text + "', '" + txtPhone.Text + "', '" + txtUser.Text + "', '" + txtPass.Text + "')");

    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
                
    MessageBox.Show("Registered successfully"); //end of code 
}

此代码应该从 Windows 表单将值添加到数据库表中,但它给出了这个错误:

System.InvalidOperationException:“ExecuteNonQuery:连接属性尚未初始化。”

标签: sql-serverc#-4.0

解决方案


推荐阅读