![](/img/trans.png)
[英]Changing the default SQL Server schema used from [dbo] to something else
[英]Changing equality to something else on SQL command
我正在开发一个Windows窗体应用程序。 我想通过用户选择更改SQL命令。 这是我的代码:
command.CommandText = "SELECT * FROM Product WHERE price = @price";
command.Parameters.AddWithValue("@price", 35);
我还想将“=”更改为“> =”或其他内容。 当我使用参数时,我会收到错误。
command.CommandText = "SELECT * FROM Urun WHERE price @equal @price";
command.Parameters.AddWithValue("@price", 35);
command.Parameters.AddWithValue("@equal", ">=");
我怎样才能做到这一点?
基本上你不能。 参数化SQL仅用于值 - 而不是表名,列名或运算符。 这是一个地方, 你可能要动态地生成SQL -但列入白名单的设置选项。
是否从位动态构建完整的SQL,或者是否有一组预先完成的SQL查询,将取决于您正在尝试做什么。 显然你仍然应该使用值的参数。
我通常使用string.format()
。
例如:
command.CommandText = string.format("SELECT * FROM Product WHERE price {0} @price", ">=");
command.Parameters.AddWithValue("@price", 35);
在实际使用中,您将“> =”替换为包含所需运算符的变量,例如:
string op = ">=";
command.CommandText = string.format("SELECT * FROM Product WHERE price {0} @price", op);
command.Parameters.AddWithValue("@price", 35);
编辑:正如Tim S.在评论中指出的那样,用户输入直接输入它并不是一个好主意。 就个人而言,我会从枚举中执行此操作,并使用用户输入来确定要使用的枚举值。 如果您决定使用直接用户输入,请确保擦除输入以避免可能的SQL注入。
string comparation=">="
command.CommandText =string.Format("SELECT * FROM Urun WHERE price {0} @price",comparation);
command.Parameters.AddWithValue("@price", 35);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.