473,837 Members | 1,579 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to replace and string in a "SELECT ... IN ()"

Hi,

I have a BIIIIIG problem with the next query:

cursor.execute( """
SELECT titem.object_id , titem.tag_id
FROM tagging_taggedi tem titem
WHERE titem.object_id IN (%s)
""",( eid_list))

eid_list is suppossed to be a list of ids = [1,5,9]

How can I make it work?

Thanks
Sep 26 '08 #1
11 2030
On Fri, 26 Sep 2008 02:32:50 -0700 (PDT), bcurtu wrote:
I have a BIIIIIG problem with the next query:

cursor.execute( """
SELECT titem.object_id , titem.tag_id
FROM tagging_taggedi tem titem
WHERE titem.object_id IN (%s)
""",( eid_list))
^
It should rather be '%'.
HTH.

--
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
Sep 26 '08 #2
Pardon?

% instead of %s?

It doesn't work... :(

On 26 sep, 12:15, Wojtek Walczak <gmin...@bzt.bz twrote:
On Fri, 26 Sep 2008 02:32:50 -0700 (PDT), bcurtu wrote:
I have a BIIIIIG problem with the next query:
* * * * cursor.execute( """
* * * * * * * * * * SELECT titem.object_id , titem.tag_id
* * * * * * * * * * FROM tagging_taggedi tem titem
* * * * * * * * * * WHERE titem.object_id IN (%s)
* * * * * * * * """,( eid_list))

* * * * * * * * * * *^
It should rather be '%'.
HTH.

--
Regards,
Wojtek Walczak,http://tosh.pl/gminick/
Sep 26 '08 #3
Wojtek Walczak a écrit :
On Fri, 26 Sep 2008 02:32:50 -0700 (PDT), bcurtu wrote:
>I have a BIIIIIG problem with the next query:

cursor.execute( """
SELECT titem.object_id , titem.tag_id
FROM tagging_taggedi tem titem
WHERE titem.object_id IN (%s)
""",( eid_list))
^
It should rather be '%'.
Please avoid such clueless advices and read the doc of the python db-api.

Sep 26 '08 #4
bcurtu a écrit :
Hi,

I have a BIIIIIG problem with the next query:

cursor.execute( """
SELECT titem.object_id , titem.tag_id
FROM tagging_taggedi tem titem
WHERE titem.object_id IN (%s)
""",( eid_list))

eid_list is suppossed to be a list of ids = [1,5,9]

How can I make it work?
You have to build your sql statement in three stages:

# stage 0: the template
sql_template = """
SELECT titem.object_id , titem.tag_id
FROM tagging_taggedi tem titem
WHERE titem.object_id IN (%s)
"""

# stage 1: build correct place_holders string for the actual number
# of items in eid_list
place_holders = ", " .join("%s" for x in xrange(len(eid_ list)))

# stage 2 : build the effective sql statement
sql = sql_template % place_holders

# ok, let's go:
cursor.execute( sql_template, eid_list)
NB : you can of course make it in a single statement, but readability
will suffer:

cursor.execute(
"""
SELECT titem.object_id , titem.tag_id
FROM tagging_taggedi tem titem
WHERE titem.object_id IN (%s)
""" % ", " .join("%s" for x in xrange(len(eid_ list))),
eid_list
)
HTH

Sep 26 '08 #5
On Sep 26, 12:23*pm, Tino Wildenhain <t...@wildenhai n.dewrote:
Hi,

Bruno Desthuilliers wrote:
bcurtu a écrit :
Hi,
I have a BIIIIIG problem with the next query:
* * * * cursor.execute( """
* * * * * * * * * * SELECT titem.object_id , titem.tag_id
* * * * * * * * * * FROM tagging_taggedi tem titem
* * * * * * * * * * WHERE titem.object_id IN (%s)
* * * * * * * * """,( eid_list))
eid_list is suppossed to be a list of ids = [1,5,9]
How can I make it work?
You have to build your sql statement in three stages:
# stage 0: the template
sql_template = """
* * SELECT titem.object_id , titem.tag_id
* * FROM tagging_taggedi tem titem
* * WHERE titem.object_id IN (%s)
"""
# stage 1: build correct place_holders string for the actual number
# of items in eid_list
place_holders = ", " .join("%s" for x in xrange(len(eid_ list)))

Hm. either ", ".join(["%s"]*len(eid_list))
or ", ".join("%s" for x in eid_list)

should produce the same, wouldn't it? :-)
[snip]
Or:

place_holders = ("%s," * len(eid_list))[ : -1]

:-)
Sep 26 '08 #6
On Fri, 26 Sep 2008 11:00:59 -0500
"Michael Mabin" <d3******@gmail .comwrote:
So we can drop a table in an in clause? How is this a use case. Cartoons
are funny but actual proof that this example using an in-clause provides an
exploit would be more helpful I think.
I'm not sure what proof you require. If you program such that users
can enter arbitrary stings into your database it is obvious that the
exploit in that cartoon can be used against you. And the point is that
it has nothing to do with IN clauses. It can be any SQL. Go read that
cartoon carefully. It says nothing about IN clauses. Consider;

"UPDATE student SET name = '%s' WHERE student_id = %s" % (name, id);

Now set name to "Robert'; DROP TABLE student;" and see what happens if
you feed that to your SQL database. Hell, just put "';" in the string
for fun.

--
D'Arcy J.M. Cain <da***@druid.ne t | Democracy is three wolves
http://www.druid.net/darcy/ | and a sheep voting on
+1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner.
Sep 26 '08 #7
On 26 Sep, 12:15, Wojtek Walczak <gmin...@bzt.bz twrote:
On Fri, 26 Sep 2008 02:32:50 -0700 (PDT), bcurtu wrote:
I have a BIIIIIG problem with the next query:
cursor.execute( """
SELECT titem.object_id , titem.tag_id
FROM tagging_taggedi tem titem
WHERE titem.object_id IN (%s)
""",( eid_list))

^
It should rather be '%'.
You're telling the inquirer to do string substitution which can be
dangerous if eid_list is built, say, from a collection of strings
taken from an untrusted source.

Sadly, SQL parameter substitution, which is done using the syntax
employed by the inquirer above (along with the unfortunate "%s"
placeholder syntax), does not really deal with sequences of values
very well. What needs to be done here, if everything should happen
relatively safely, is that the query string should be made to contain
the appropriate number of placeholders between the brackets, with
commas separating them as demanded by the syntax of SQL. Then, the
values should be correctly taken from eid_list by the execute method,
although for portability between different database modules, whose
authors seem to have differing views on what kind of object can be
given containing the parameters, I'd recommend converting eid_list to
a tuple.

Bruno and Tino thrash out some kind of working solution, I think.

Paul
Sep 26 '08 #8
On Fri, 26 Sep 2008 14:04:35 -0500
"Michael Mabin" <d3******@gmail .comwrote:
Doesn't it depend on where and why you intend to execute the code?
Obviously some SQL is more at risk for exploit when the input is from the
screen on a web page than if you were running parameterized code in a
controlled batch environment. Or if you were writing code generators (which
is what I happen to do) which won't be run by the general public.

Incidentally, couldn't input field edits prevent such exploits prior to
interpolation?
I encourage my competitors to program that way.

--
D'Arcy J.M. Cain <da***@druid.ne t | Democracy is three wolves
http://www.druid.net/darcy/ | and a sheep voting on
+1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner.
Sep 26 '08 #9
Hi,

Michael Mabin wrote:
If the inputs are edited prior to the construction of the string and
these fields are used for more than one update then it's not an exploit.
It's simply a matter not repeating yourself when coding.
In python we do not fear that.
In this particular case too, we're talking about a list of integers that
gets inserted into a string. If the list is validated prior to its
Its a list, if it indeed has integers in it is uncertain. It is so very
easy to check that that it doesnt even make sense to write such lengthy
emails about how bad you want to avoid it. Just do it. And even more so
if you are telling others how to do things make sure they do not so easy
shoot themselfes in their feet.
insertion into an SQL statement then there is no exploit. If I write a
batch program (not a web program) that retrieves this list of integers
from other sources and validates the data prior to using it in an SQL
statement, that should be sufficient.
This might be well true but if you have a look at your original
contribution you see that all these your asumtions are just not in.
As far as wrong and right is concerned. I think it's more about doing
what is appropriate according to the circumstances. As a rule you
If its easy to do, why not just doing it correctly (or robust) in all
circumstances to just avoid overlooking a case?
should only code what is appropriate for the circumstances. If it's
appropriate to code more simply without introducing unnecessary
complexity you should do so.
But you did not tell us about your asumtations about the circumstances.
I work in the data warehousing ETL world, where we have to perform field
edits or transformations to load source data into databases. If I'm
Thats wrong. You do not "edit" fields. You have a validating type path
and _always_ the database is most authoritative about what it accepts.
Any other concept is just wrong and outright dangerous. There are
many examples of how this works out (just check bugtraq)
already performing edits on these fields and if these fields are going
to be used for more updates downstream, it's wasteful to perform them
again when I build the SQL insert with the list and execute it.
I still don't know what you mean by "edit" ;) If you mean filter out
special chars with for example replace("bad stuff","good stuff") check
your idea again, this is not going to work. (google for default permit)
Finally, whatever happened to the practice of granting appropriate
privileges to IDs that perform database operations? Shouldn't the
person acting in the capacity of DBA ensure that the user updating or
retrieving data from the database does not have DROP, ALTER, or CREATE
privileges on that database?
This of course is another layer which should be added - but you would
not need to - you edited the fields, right? ;)

Sorry, it was not meant to put you to the wall but you insist so much
on your still dangerous solution while top posting the hell out of
this thread I just could not ignore it ;)

T.

Sep 27 '08 #10

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

Similar topics

0
1357
by: Rick Brandt | last post by:
Here is a simplified example of what I am passing to a Java SAX parser within a servlet via an HTTPRequest... <?xml version="1.0"?> <Record> <ID>1092853685</ID> <Notes><!]></Notes> </Record> I get the following error in the server's log output...
6
56333
by: vigi98 | last post by:
Hello all, Can someone confirme that this: var strURLpiece = "UK & Ireland"; strURLpiece.replace("&", "%26"); replaces all occurrence of the character & by %26 in strURLpiece, ie that strURLpiece becomes "UK %26 Ireland" ? Thanks a lot.
3
10514
by: asd987 | last post by:
Hi, Can anyone tell me if "replace" is supported by Access 97? I use the Dutch version and get the errormessage "sub or function not supported". Or is the Professional Edition needed? Thanks.
2
4578
by: ad | last post by:
Hello, if I try this ((StringBuilder)sb).Replace("a", "aa"); I get OutOfMemoryException raised if sb contains at least one "a"... It seems like StringBuilder 'seeker' doesn't move to the end of replacement string but it moves to the second character of the replacement string...
6
29637
by: Marty | last post by:
Hi, I would like to replace "\r\n" by "_" within a specific string. I tried : strMyString.Replace('\r', '_'); strMyString.Replace('\n', '_'); or strMyString.Replace(System.Environment.NewLine, '_');
6
1381
by: Dean Slindee | last post by:
Private NameLastFirst as object = "Public, John Q." NameLastFirst = Replace(LastName, "'", "''") If NameLastFirst contains "Public, John Q." before the above Replace, it will contain "Public" after the Replace. At least that's how it's working in my version of VS.NET. That does not seem right to me. Am I missing something? Note that the replacement character(s) are *apostrophes*, not *commas*
2
3332
by: John Nagle | last post by:
I'm trying to clean up a bad ASCII string, one read from a web page that is supposedly in the ASCII character set but has some characters above 127. And I get this: File "D:\projects\sitetruth\InfoSitePage.py", line 285, in httpfetch sitetext = sitetext.encode('ascii','replace') # force to clean ASCII UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 29151: ordinal not in range(128)
5
1843
by: Curious | last post by:
I have: if (temp.Contains("Account") == true) { temp.Replace("Account", "Client"); } The "Account" is not replaced by "Client" after this operation. I used
3
1941
by: Curious | last post by:
I have another question about Regular Expression. If I use: if (temp.Contains("Ending") == true) { temp = System.Text.RegularExpressions.Regex.Replace(temp, "Ending", "Beginning"); } It seems that while "Ending" is replaced with "Beginning", it also
0
9843
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9682
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10570
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10626
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10273
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5670
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4474
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4041
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3124
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.