方法在ASP.Net中返回空字符串

时间:2015-08-06 00:43:30

标签: c# sql asp.net sql-server database

我在使用这种方法时遇到了麻烦。它返回空字符串,这有什么问题?

我有这个方法:

public static string GetData(string Table1, string Column1, string WhereColumn, string WhereValue)
{
    Table1 = Methods.cleaninjection(Table1); // Some injection method that cleans the string

    SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["connection"].ConnectionString);

    SqlCommand command = new SqlCommand("SELECT " + "@Column1" + " FROM " + Table1 + " WHERE " + "@WhereColumn" + " = " + "@WhereValue", connection);
    command.Parameters.AddWithValue("Column1", Column1);
    command.Parameters.AddWithValue("WhereColumn", WhereColumn);
    command.Parameters.AddWithValue("WhereValue", WhereValue);

    try
    {
        if ((connection.State == ConnectionState.Closed) || (connection.State == ConnectionState.Broken))
        {
            connection.Open();
        }
        string veri = Convert.ToString(command.ExecuteScalar());
        return veri;
    }
    finally
    {
        connection.Close();
    }
}

当我运行它时,命令字符串如下所示:

  

SELECT @ Column1 FROM Table1 WHERE @WhereColumn = @WhereValue

看起来很正确,但我找不到什么问题 有什么想法吗?

1 个答案:

答案 0 :(得分:2)

如评论所示,您无法参数化列名和表名。相反,做字符串连接:

"SELECT " + Column1 + " FROM " + Table1 + " WHERE " + WhereColumn + " =  @WhereValue";

以下是您的代码应该如何:

public static string GetData(string Table1, string Column1, string WhereColumn, string WhereValue)
{
    Table1 = Methods.cleaninjection(Table1); // My injection method that cleans the string

    string sql = "SELECT " + Column1 + " FROM " + Table1 + " WHERE " + @WhereColumn + " =  @WhereValue";

    using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["connection"].ConnectionString))
    {
        using (SqlCommand command = new SqlCommand(sql, connection))
        {
            command.Parameters.Add("@WhereValue", SqlDbType.VarChar, 50).Value = WhereValue;

            connection.Open();

            string veri = Convert.ToString(command.ExecuteScalar());
            return veri;
        }
    }
}

注意:

  1. 请不要使用AddWithValue。请改用Parameters.Add()。根据这个article:
  2.   

    AddWithValue()函数存在问题:它必须推断   查询参数的数据库类型。这是事情:   有时它会弄错。

    1. 将您的对象包裹在Using中,以确保正确清理资源。
    2. 出于其他安全目的,您可以将列名和表名包装在方括号[]中。