我想我在这里的某个地方犯了一个相当业余的错误,但我无法让 SQL 参数在 C# 中可靠地工作。考虑以下代码:
protected string[] Query(string dataToFind, string tableName, string fieldToCheck, string fieldToReturn)
{
SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
SqlDataReader dataReader = null;
SqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT " + fieldToReturn + " FROM " + tableName + " WHERE " + fieldToCheck " = '" + dataToFind "'";
try
{
connection.Open();
dataReader = command.ExecuteReader();
etc...
这会按照您的预期执行,fieldToReturn
从 table返回tableName
。但是,我知道这很容易受到 SQL 注入的影响,避免这种情况的正确方法是使用参数。所以我将我的代码更改为以下内容:
protected string[] Query(string dataToFind, string tableName, string fieldToCheck, string fieldToReturn)
{
SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
SqlParameter[] parameters = new SqlParameter[4];
parameters[0] = new SqlParameter("@dataToFind", dataToFind);
parameters[1] = new SqlParameter("@name", tableName);
parameters[2] = new SqlParameter("@fieldToCheck", fieldToCheck);
parameters[3] = new SqlParameter("@fieldToReturn", fieldToReturn);
SqlDataReader dataReader = null;
SqlCommand command = connection.CreateCommand();
command.Parameters.AddRange(parameters);
command.CommandText = "SELECT @fieldToReturn FROM @tableName WHERE @fieldToCheck = @dataToReturn";
try
{
connection.Open();
dataReader = command.ExecuteReader();
etc...
如果我的数据库中有 3 个匹配项,则第一个代码示例返回 3 个匹配项。第二个代码返回 0 个结果?!
我是不是很愚蠢并且遗漏了一些明显的东西?