473,382 Members | 1,766 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

MSSQL LIKE and IN statements in ADO problem

Helo guys,
I am trying to query the MSSQL DB using ADO.
I am not able to make the LIKE statement fetch the correct results.
Can anyone tell me what I need to do to get this working?
Below is the code snippet:

import win32com.client
const = win32com.client.constants

#conn = establish SQL connection
cmd = win32com.client.Dispatch("ADODB.Command")
cmd.ActiveConnection = conn

name = '@fname'
value = "'raj"
p=cmd.CreateParameter(name, const.adVarchar, Value=value)
cmd.Parameters.Append(p)
cmd.CommandText = \
"SELECT * FROM tb_name WHERE firstname LIKE @fname"
cmd.CommandType = const.adCmdText
(rs, dummy) = cmd.Execute()
while not rs.EOF:
print rs.Fields('firstname').Value
rs.MoveNext()
rs.Close()

I originally was using the '%?%' symbol but that did not work and now,
i changed it to @fname but this returns a traceback telling that I need
to declare @fname.

Also, I have another probelm with using the "IN" SQL statement.

I appreciate your help in advance,

Thank you,
Raja Raman

Jan 18 '06 #1
16 2702
Can't you get rid of the Create Parameter part and directly pass along
the value you are looking for? Something like...

name = 'raj'
cmd.CommandText= \
"SELECT * FROM tb_name WHERE firstname LIKE %%%s" % name

This way the value of the name variable gets passed along when the
CommandText method is invoked. BTW, this looks too painfully much like
Visual Basic than Python :-) Just kidding (kind of)

Jan 18 '06 #2
Sorry forgot to explain that with the string substitution stuff you can
escape the percent sign by doubling it up. In my example I wanted to
retain the leading percent sign before the value, in this case I wanted
LIKE %raj to appear. So I doubled it up. That's why there are three
percent signs in a row. The last one is the one associated with the
string substitution for the name variable. Make sense?

Jan 18 '06 #3
gregarican wrote:
Sorry forgot to explain that with the string substitution stuff you can
escape the percent sign by doubling it up. In my example I wanted to
retain the leading percent sign before the value, in this case I wanted
LIKE %raj to appear. So I doubled it up. That's why there are three
percent signs in a row. The last one is the one associated with the
string substitution for the name variable. Make sense?

Now Google for "sql injection vulnerability" and tell us why this is a
bad idea.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/

Jan 18 '06 #4
Yes, Steve you have a very good point.
Gregarcian, I am using the parameterized SQL to avoid such
vulunerability.
for example in your example use
name = "%'WAITFOR DELAY '00:00:03'--%"
and directly substitute it to the statement
"select * from table_name where name like '%s' " % (name)
The server will have to wait for three seconds and will return all the
rows in the table,
which is unwanted.
I am trying to use parameterized statements to avoid these sort of SQL
injection problems
and have not managed yet to fix the LIKE and IN statement problems.

/Raja Raman

Jan 18 '06 #5
Steve Holden wrote:
Now Google for "sql injection vulnerability" and tell us why this is a
bad idea.


The original poster didn't specify if they were writing
production-level code on in Internet-facing server so I didn't exactly
infer a context. You are correct in your statement. I was just pointing
out how substitutions operate if they were indeed an option.

Jan 18 '06 #6
Hi Gregarican,
I am the original poster and yes this is a production code level
problem.
Do u have inputs for a solution?
/Raja Raman

Jan 18 '06 #7

<ra*****@hotmail.com> wrote in message news:11**********************@g43g2000cwa.googlegr oups.com...
Helo guys,
I am trying to query the MSSQL DB using ADO.
I am not able to make the LIKE statement fetch the correct results.
Can anyone tell me what I need to do to get this working?
Below is the code snippet:

import win32com.client
const = win32com.client.constants

#conn = establish SQL connection
cmd = win32com.client.Dispatch("ADODB.Command")
cmd.ActiveConnection = conn

name = '@fname'
value = "'raj"
p=cmd.CreateParameter(name, const.adVarchar, Value=value)
cmd.Parameters.Append(p)
cmd.CommandText = \
"SELECT * FROM tb_name WHERE firstname LIKE @fname"
cmd.CommandType = const.adCmdText
(rs, dummy) = cmd.Execute()
while not rs.EOF:
print rs.Fields('firstname').Value
rs.MoveNext()
rs.Close()

I originally was using the '%?%' symbol but that did not work and now,
i changed it to @fname but this returns a traceback telling that I need
to declare @fname.

Also, I have another probelm with using the "IN" SQL statement.

I appreciate your help in advance,

Thank you,
Raja Raman


The wildcards are part of your input string, so you'd need
value = "%raj%" (looks like there was an extraneous single
quote in the original) and your sql would be
"SELECT * FROM tb_name WHERE firstname LIKE ?"
Named parameters are usually used for calling
stored procedures. As far as I know, you can't use them
with plain Sql.

hth
Roger


----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= East/West-Coast Server Farms - Total Privacy via Encryption =---
Jan 18 '06 #8
Well, the raw TSQL would be:

select * from tb_name where firstname like '%raj%'

I think that would more translate to:

name = "raj"
cmd.CommandText = "SELECT * FROM tb_name WHERE firstname like '%%%s%%'" % name

Perhaps issuing a print statement of the CommandText would help for future runs
to determine if this is valid TSQL syntax?

-Pete

"gregarican" <gr*********@gmail.com> wrote:
Can't you get rid of the Create Parameter part and directly pass along
the value you are looking for? Something like...

name = 'raj'
cmd.CommandText= \
"SELECT * FROM tb_name WHERE firstname LIKE %%%s" % name

This way the value of the name variable gets passed along when the
CommandText method is invoked. BTW, this looks too painfully much like
Visual Basic than Python :-) Just kidding (kind of)

Jan 18 '06 #9
Hello Steve, Roger and Pete,
Nice to read your reply. Well, I can do an assert check for
integers and then filter out hazardous SQL injection characters for
varchars and do a direct substitution of the filtered values with the
SQL statement.

But by using ADO, input strings can be treated as what they are
intended to be by adding values to the CreateParameter statement whe we
do an Execute.
This way I thought I need not care about what kind of input I get from
the client, and I will be able to use them blindly to form a dynamic
query.
Thus producing a more general solution for SQL injection prone areas.

Also, when it comes to filtering of hazardous characters, I think its
better to allow only those characters one needs than to filter out SQL
injection specific characters.
But the problem is we have all kinds of special characters stored in
our DB and filtering out characters will only result in wrong output.
So, I have to rule out this case.

With the DB API, yes I had a quick look at the code and the dynamic
formation of the SQL statement does not seem to have support for IN
statements.
I am not sure about the LIKE statement though. Maybe, they do support
it. So, I need to take a closer look at the adoapi.py file before
concluding.

To the concerned:
value = '%raj%'
"select * from table_name where firstname LIKE '%s' " % value

works just fine, the result set contains all the first names that
contains 'raj'
How should we do this using createparameter in python?
There should be a wasy toa chieve this in ADO using python.
C# has a way to do this using ADO.Net.

Please keep providing inputs, in the mean time I will also do some
research on this problem and get back to you if I find a solution.

Thanks!
/Raja Raman

Jan 19 '06 #10
This does not seem to work well Roger
value = '%raj%'
cmd.CommandText = "select * from table_name where firstname LIKE ?"

result is 0 where I expected 4
/Raja Raman

Jan 19 '06 #11
Thanks. Please keep us posted. For some of my potentially exposed areas
I was just doing regex lookups against the input parameter to filter
out possible SQL injection keywords. Obviously not as elegant and
efficient as using ADO parameters to strictly define the data that
should be coming into the SQL statement. Playing around with the code
you provided yesterday I had problems using an ADO parameter as a
condition of the SQL LIKE statement. Not sure if that's an ADO
limitation, a Python ADO limitation, or my relative ignorance :-)

Jan 19 '06 #12
Ok guys! The problem seems to be much easier to be solved than first
thought. -->Shoot<--
Using the correct CreateParameter statement seems to do the trick.
For example creating the parameter as
cmd.CreateParameter(name,const.adVarChar, const.adParamInput, Size=16,
Value=value[i])
# Name, Type, Direction, Size, Value

works pretty good with the LIKE statement

For the IN statement I have not yet found a good way. As of now
in am looping through the values and creating various parameters
Snippet:
##
##Global initialization
##
typeMap= {
types.IntType: const.adInteger,
types.LongType: const.adBigInt,
}

query = "SELECT * FROM tb_name WHERE firstname IN %(in_params)"

##
##add parameters and construct the ? values for the in statements
##Note the code below is a pseudo type thing and can contain syntax
errors
##
in_parameters = [1,2,3,4,5]
n_index = 0
in_params = ''

for i in in_parameters:
in_params += '?,'
name = 'name_%s' % i
p=cmd.CreateParameter(name, typeMap[type(i)], const.adParamInput,
Size=16, Value=i) # Name, Type, Direction, Value
cmd.Parameters.Append(p)
query = query % {'in_params': in_params[:-1]}

Any inputs to improve the IN statement logic?
My dream is to use just one create parameter for the SQL list
so that the query looks like
query = "SELECT * FROM tb_name WHERE firstname IN ?"
Nice and easy...

:-)
Thanks in advance!
/Raja Raman

Jan 19 '06 #13
The IN statement logic is a good mind exercise if there are multiple
parameters that needed to be brought in. Below is the code that fixed
the LIKE statement logic where you needed an ADO parameterized query
used. Apparently the percent signs don't have to be referenced anywhere
in the code, as my tests ran successfully without them:

-------------------------------------------------
import win32com.client
from adoconstants import *
conn = win32com.client.Dispatch(r'ADODB.Connection')
conn.ConnectionString = "Driver={SQL
Server};Server=(local);Database=myDB;Trusted_Conne ction=yes;"
conn.Open()
if conn.state == adStateOpen:
print "Connected to database..."
else:
print "Not connected!"
exit
cmd=win32com.client.Dispatch(r'ADODB.Command')
cmd.ActiveConnection=conn

name = '@fname'
value = 'raj'
param=cmd.CreateParameter(name, adVarChar, adParamInput, 200, value)
cmd.Parameters.Append(param)
cmd.CommandText = "SELECT first, last FROM myTable WHERE first like ?"
cmd.CommandType = adCmdText
(rs, dummy) = cmd.Execute()
rowCount = 0
while not rs.EOF:
print rs.Fields('first').Value, rs.Fields('last').Value
rowCount=rowCount+1
rs.MoveNext()
print "%s records returned." % rowCount
rs.Close()

Jan 19 '06 #14
Hi Gregarican,
Thanks for sharing your code. One needs to add the % signs if one
wants to do wildcard searches using LIKE in the SQL server.
Do as Roger and Steve suggested '%raj%', now you can find the names
containing the word raj anywhere in the column.
just value = 'raj' is only going to fetch you fnames that == 'raj'
Originally my problem was using the LIKE statement itself. But I guess
you already know.
/Raja Raman

Jan 19 '06 #15
Raja Raman Sundararajan wrote:
[...]
Any inputs to improve the IN statement logic?
My dream is to use just one create parameter for the SQL list
so that the query looks like
query = "SELECT * FROM tb_name WHERE firstname IN ?"
Nice and easy...

Some DBAPI modules will indeed allow you to use a list or set parameter
for this purpose, but not all.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/

Jan 19 '06 #16
Raja Raman wrote:
Hi Gregarican,
Thanks for sharing your code. One needs to add the % signs if one
wants to do wildcard searches using LIKE in the SQL server.
Do as Roger and Steve suggested '%raj%', now you can find the names
containing the word raj anywhere in the column.
just value = 'raj' is only going to fetch you fnames that == 'raj'
Originally my problem was using the LIKE statement itself. But I guess
you already know.



Duhhh on my part. A little behind the curve as I'm recouping from adult
chicken pox. Coding from the sickbed isn't ideal I suppose :-)

Jan 19 '06 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: badz | last post by:
Hi frenz Lately I try to use MSSQL and PHP , the problem arise when PHP try to read MSSQL field with 'image' data type, header("Content-type: image/jpeg"); // act as a jpg file to browser I...
7
by: mj | last post by:
Hello, thanks for the help. I am running a WinXP Pro w/ SP2 (my home computer, with ZoneAlarm firewall) Apache 2.0.52 MySQL 4.1.7 PHP 5.1.0-dev I have developed a PHP/MySQL web app that...
1
by: JackTorrance | last post by:
Hi i have a problem with IIS6 and MSSQL and i hope that someone can help me. this is the configuration: Windows 2003 IIS6 MSSQL 7.0 Standard Edition ADO 2.5
8
by: Yusuf INCEKARA | last post by:
I have a stored procedure : CREATE PROCEDURE STP_GETSTORELIST @RETCUR CURSOR VARYING OUTPUT AS set @RETCUR = CURSOR FORWARD_ONLY STATIC FOR SELECT ID,STORE_NAME FROM T_INF_STORE ORDER BY...
2
by: wildfyre53207 | last post by:
Here is our problem... We are doing a lot of selects against a table that has one large field in it. If we do a select against all the fields except for description, the query comes back...
9
by: Advo | last post by:
Im having major problems trying to connect to a mssql database thats hosted on our server. I've got the ip, username, password and database name, yet no matter what i try, I cant seem to...
14
by: guswebb | last post by:
Hi. I'm a newbie to PHP and am having a few problems as follows... I have installed PHP successfully on server 1 which is running IIS 6 (W2k3) and hosting multiple sites, some of which connect to...
11
by: Icemokka | last post by:
Hi, I'm need to upload a big file ( 600Mb+ ) to a BLOB field in MSSQL 2005. My code looks like this : fs = New FileStream(sFilePath, FileMode.Open) Dim ByteArray(fs.Length) As Byte...
0
by: Harris Kosmidhs | last post by:
Hello. I 'm working on a project which has developed a huge program. Some customers use DB2 as database, and others oracle. So far so good and everything works ok. Now there's a demand on...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.