将c#全局变量传递给sql查询

时间:2016-02-23 22:17:44

标签: c# mysql asp.net-mvc-5 global-variables

我有一个Auto类,如下所示

namespace UI.Controllers
{
    public class Auto
    {
       user = 'raven';

    public static string user
        {
            get;
            set;
        }
    }
}

既然我已经将变量提到了全局变量,我可以通过这种方式使用它在其他.cs文件中使用它。

string getusername = Auto.user;

当我尝试使用此用户名查询SQL表时存在问题。这是我打算做的。

SELECT * FROM users_table WHERE NAME = [put user details here];

[]括号表示用户名。即乌鸦应该动态放置在那里

我尝试了下面的变化,但它没有用。

SELECT * FROM users_table WHERE NAME= "@Auto.user";
SELECT * FROM users_table WHERE NAME= "Auto.user";
SELECT * FROM users_table WHERE NAME= Auto.user;
SELECT * FROM users_table WHERE NAME= & Auto.user &;
SELECT * FROM users_table WHERE NAME= & "Auto.user" &;

它给出了一个错误,指出The name Auto doesn't exist in current context

如果我正在尝试正确的方式,有人可以建议我。 ?

这是实际的SQL查询

readonly string USERNAME = @"SELECT * FROM users_table WHERE NAME = ";


public List<Users> GetUserName()
    {
        string query = USERNAME + "@name";
        return this._users.Get(query, new { name = Auto.user });
    }

1 个答案:

答案 0 :(得分:2)

如果您只想将Auto.user值传递给查询变量,请使用string.Format

readonly string USERNAME = @"SELECT * FROM users_table WHERE NAME = {0}";

public List<Users> GetUserName()
{
    var query = string.Format(USERNAME, Auto.user);
    return this._users.Get(query);
}

如果没有更深入地了解查询在查询执行器中的完成方式,我无法找到另一种方法。如果您使用有关_users类型和实现的更多信息更新问题,我可以给您一个更好的答案。

相关问题