在防御 SQL 注入方面,对于更简单的查询,以下策略之一是否比另一个更有效?:
使用参数化:
using (SqlCommand command = new SqlCommand(@"SELECT * FROM @table", connection)) { command.Parameters.AddWithValue("@table", table_name); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { ... } } }
使用
string.Format
:using (SqlCommand command = new SqlCommand(string.Format(@"SELECT * FROM {0}",table_name), connection)) using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { ... } }