且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用SQL语句的字符串变量

更新时间:2023-01-19 22:55:25

您只需做到这一点。

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.