ExecuteNonQuery:未初始化Connection属性

时间:2017-07-21 04:00:18

标签: c# sql .net

如何解析ExecuteNonQuery:未初始化Connection属性。我已经做了我的cmd.Connection = con;这是我的代码请帮忙

Private void button1_Click(object sender, EventArgs e)
{
    if (img_file != null)
    { 

FileStream fs = new FileStream(img_file, System.IO.FileMode.Open, System.IO.FileAccess.Read);
        byte[]image = new byte[fs.Length];

        fs.Read(image,0,Convert.ToString(fs.Length));
        fs.Close();
        SqlCommand cmd = new SqlCommand("INSERT INTO member_details (name,address,email,phone_number,picture) VALUES('"+textBox1.Text+"', '"+textBox2.Text+"', '"+textBox3.Text+"', @pic)", con);
        SqlParameter prm = new SqlParameter("@pic", SqlDbType.VarBinary, image.Length, ParameterDirection.Input, false, 0,0, null, DataRowVersion.Current, image);
        cmd.Parameters.Add(prm);
        cmd.Connection = con;
        cmd.ExecuteNonQuery();
        con.Close();
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码作为参考来修复您的代码:

string connetionString = null;
SqlConnection cnn ;
SqlCommand cmd ;
string sql = null;

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Your SQL Statemnt Here";

cnn = new SqlConnection(connetionString);
try
{
    cnn.Open();
    cmd = new SqlCommand(sql, cnn);
    cmd.ExecuteNonQuery();
    cmd.Dispose();
    cnn.Close();
    MessageBox.Show (" ExecuteNonQuery in SqlCommand executed !!");
}
catch (Exception ex)
{
    MessageBox.Show("Can not open connection ! ");
}

您可以通过

简单地初始化和关闭连接
using(SqlConnection con = new SqlConnection(connectionstring))
{
--write all your command n execution code here---;
}

除此之外,还有一个建议,你需要使用参数化查询或Stored Proc with paramerts来避免SQLInjection:

引用SQLInjection:https://www.veracode.com/security/sql-injection