如何连接字符串以进行查询 [英] how to concatenate string for query

查看:82
本文介绍了如何连接字符串以进行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好

i在网页上有这个代码

我的问题:

数据库中有2条记录其中一条有ip = 99和另一个有ip = 000099作为varchar

但是当我重新设置ip = 99我得到ip = 000099的记录

i尝试使用

string .Concat();
string .Format();
string .Append();
stringBuilder



但没有变化

我的代码:

  try  
{
OleDbConnection myOleDbConnection = new OleDbConnection(connectionString);
myOleDbConnection.Open();
OleDbCommand myOleDbCommand = myOleDbConnection.CreateCommand();
string str = 99;
myOleDbCommand.CommandText = select sale_price,postion from item where ip = + str;
OleDbDataReader dr = myOleDbCommand.ExecuteReader();
dr.Read();
/// ////////获得结果
dr 。关();
myOleDbConnection.Close();

}
catch
{

}

解决方案

您忘记将str包含在带单引号的where子句中。但是你不应该直接将变量注入sql查询。相反,您应该使用参数化查询 [ ^ ]以防止sql注射 [ ^ ]。


我试图连接命令文本



DONT! !!!



使用参数化查询。每次。它始终有效。


因为你的IP类型是varchar,你应该以这种方式纠正SQL:

 myOleDbCommand.CommandText =  string  .Format(  select sale_price,postion from item where ip ='{0}',str); 


Hello
i have this code in web page
my problem:
there is 2 records in the database one of it have ip=99 and the other one have ip=000099 as varchar
but when i requset ip=99 i get record for ip=000099
i tried to concatenate the command text using

string.Concat();
string.Format();
string.Append();
stringBuilder


but no change
my code:

try
                {
                    OleDbConnection myOleDbConnection = new OleDbConnection(connectionString);
                    myOleDbConnection.Open();
                    OleDbCommand myOleDbCommand = myOleDbConnection.CreateCommand();
                  string str="99";
                    myOleDbCommand.CommandText = "select sale_price,postion from item where ip=" + str;
                    OleDbDataReader dr = myOleDbCommand.ExecuteReader();
                    dr.Read();
///////////get results
 dr.Close();
                    myOleDbConnection.Close();

                }
                catch 
                {
                    
                }

解决方案

You have forgotten to enclose your str in the where clause with single quote. But you should not inject variable directly into the sql query. Instead, you should use parameterized query[^] to prevent sql injection[^].


"i tried to concatenate the command text"

DON"T!!!!

Use a parameterized query. Every time. It always works.


Because your IP type is varchar, you should correct the SQL in this way:

myOleDbCommand.CommandText = string.Format("select sale_price,postion from item where ip='{0}'", str);


这篇关于如何连接字符串以进行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆