如何在sql语句中使用字符串变量 [英] How to use string variable in sql statement
本文介绍了如何在sql语句中使用字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 WPF 应用程序
I have a WPF Application in which I am getting
string someone = TextBox.text;
我想在以下查询中使用它
I would like to use this in the following query
query = " Select * From Table Where Title = someone "
我应该如何在查询中使用变量某人?
How should I go about using the variable someone in the query?
推荐答案
你可以这样做
query = "Select * From Table Where Title = " + someone;
但这很糟糕,而且会让你面临 SQL 注入
But that is bad and opens you to SQL Injection
您应该只使用参数化查询
You should just use a parameterized query
这样的事情应该会让你开始
Something like this should get you started
using (var cn = new SqlClient.SqlConnection(yourConnectionString))
using (var cmd = new SqlClient.SqlCommand())
{
cn.Open();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * From Table Where Title = @Title";
cmd.Parameters.Add("@Title", someone);
}
来自 Jon Skeet 的回答,因为他的回答比我的更完整
From Jon Skeet's answer since his was more complete than mine
查看SqlCommand.Parameters 了解更多信息.
基本上,出于各种原因,您不应将值嵌入 SQL 本身:
Basically you shouldn't embed your values within the SQL itself for various reasons:
- 混合代码和数据是不雅的
- 它让您面临 SQL 注入除非你非常小心地逃避
- 您必须担心数字、日期和其他内容的格式和 i18n 详细信息次等
- 当查询保持不变时,只有值改变,优化器要做的工作更少——它可以查找直接使用先前优化的查询,因为它将完美匹配SQL 的术语.
这篇关于如何在sql语句中使用字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文