天天看點

SqlCommand 參數化輸入SQL語句

。。用參數化方法建構SQL語句,可以不用去拼接SQL語句,那樣很容易出錯

雖然我之前項目都是拼接的。。。汗中

其次還可以防止SQL語句注入,在我的項目裡,update,delete,insert 和帶條件的select 都使用了參數建構SQL語句,像"select * from table"之類的句子,就不用了。。。SqlCommand sqlcom =new SqlCommand( "update homework set tid=@tid,title=@title,content=@content where hid=@hid");

// string sqlcomd = "update homework set tid='" + tid + "',title='" + title + "',content='" + content +"' where hid='" + hid + "'";

sqlcom.Parameters.Add(new SqlParameter("@tid", tid));

sqlcom.Parameters.Add(new SqlParameter("@hid", hid));

sqlcom.Parameters.Add(new SqlParameter("@title", title));

sqlcom.Parameters.Add(new SqlParameter("@file", file));

SqlConnection conn = getConnection();

command.Connection = conn;

try

{

conn.Open();

command.ExecuteNonQuery();

}

catch (Exception ex)

{

throw ex;

}

finally

{

conn.Close();

command.Dispose();

}

}