如何使用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);
}
从乔恩斯基特的回答,因为他比我更完整
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注入
攻击混合代码和数据 - 再非常小心转义
- 您不用担心格式和国际化细节的东西像数字,日期和
时间等 - 在当前查询保持不变,只值
更改,优化有较少的工作要做 - 它可以直接查找
先前优化的查询,因为它会在
而言是绝配
- It's inelegant to mix code and data
- It opens you up to SQL injection attacks unless you're very careful about escaping
- You have to worry about formatting and i18n details for things like numbers, dates and times etc
- When the query remains the same with only the values changing, the optimizer has less work to do - it can look up the previous optimized query directly as it'll be a perfect match in terms of the SQL.
这篇关于如何使用SQL语句的字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文