473,763 Members | 7,727 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

escape single and double quotes

I'm working with a Python program to insert / update textual data into a
PostgreSQL database. The text has single and double quotes in it, and I
wonder: What is the easiest way to escape quotes in Python, similar to
the Perlism "$str =~ s/(['"])/\\$1/g;"?

I tried the re.escape() method, but it escapes far too much, including
spaces and accented characters. I only want to escape single and double
quotes, everything else should be acceptable to the database.
--
Leif Biberg Kristensen
http://solumslekt.org/
Jul 18 '05 #1
7 22783
> I'm working with a Python program to insert / update textual data into a
PostgreSQL database. The text has single and double quotes in it, and I
wonder: What is the easiest way to escape quotes in Python, similar to
the Perlism "$str =~ s/(['"])/\\$1/g;"?

I tried the re.escape() method, but it escapes far too much, including
spaces and accented characters. I only want to escape single and double
quotes, everything else should be acceptable to the database.


You don't need to escape text when using the Python DB-API.
DB-API will do everything for you.
For example:
SQL = 'INSERT into TEMP data = %s'
c.execute(SQL, """ text containing ' and ` and all other stuff we might
read from the network""")

You see, the SQL string contains a %s placeholder, but insetad of executing
the simple string expansion SQL % """....""", I call the execute method
with the text as a second *parametar*. Everything else is magic :).

--
damjan
Jul 18 '05 #2
Hey there,

str.replace('"' , '\\"').replace( "'", "\\'")

HTH, jbar
Jul 18 '05 #3
Damjan skrev:
You don't need to escape text when using the Python DB-API.
DB-API will do everything for you.
For example:
SQL = 'INSERT into TEMP data = %s'
c.execute(SQL, """ text containing ' and ` and all other stuff we
might
read from the network""")

You see, the SQL string contains a %s placeholder, but insetad of
executing the simple string expansion SQL % """....""", I call the
execute method with the text as a second *parametar*. Everything else
is magic :).


Sure, but does this work if you need more than one placeholder? FWIW,
here's the whole script. It will fetch data from the table name_parts
and pump them into the "denormaliz ed" table names ( a real SQL guru
would probably do the same thing with one single monster query):

import psycopg
from re import escape

connection = psycopg.connect ("dbname=slekta ", serialize=0)
sql = connection.curs or()

sql.execute("se lect * from name_parts")
result = sql.fetchall()
for row in result:
if row[2] == 1: # name part = 'prefix'
query = ("update names set prefix='%s' where name_id=%s" % \
(escape(row[4]), row[1]))
elif row[2] == 2: # name part = 'given'
query = ("update names set given='%s' where name_id=%s" % \
(escape(row[4]), row[1]))
elif row[2] == 3: # name part = 'surname'
query = ("update names set surname='%s' where name_id=%s" % \
(escape(row[4]), row[1]))
elif row[2] == 4: # name part = 'suffix'
query = ("update names set suffix='%s' where name_id=%s" % \
(escape(row[4]), row[1]))
elif row[2] == 5: # name part = 'patronym'
query = ("update names set patronym='%s' where name_id=%s" % \
(escape(row[4]), row[1]))
elif row[2] == 6: # name part = 'toponym'
query = ("update names set toponym='%s' where name_id=%s" % \
(escape(row[4]), row[1]))
sql.execute(que ry)
sql.commit()
connection.clos e()
--
Leif Biberg Kristensen
http://solumslekt.org/
Jul 18 '05 #4
Leif B. Kristensen wrote:
Damjan skrev:
For example:
SQL = 'INSERT into TEMP data = %s'
c.execute(SQL, """ text containing ' and ` and all other stuff we
might read from the network""")
Sure, but does this work if you need more than one placeholder?
Yup.
FWIW, here's the whole script. It will fetch data from the table name_parts
and pump them into the "denormaliz ed" table names ( a real SQL guru
would probably do the same thing with one single monster query):

import psycopg
from re import escape

connection = psycopg.connect ("dbname=slekta ", serialize=0)
cursor = connection.curs or()

cursor.execute( "select * from name_parts")
result = cursor.fetchall ()

kind = 'prefix', 'given', 'surname', 'suffix', 'patronym', 'toponym'

for row in result:
if 0 < row[2] <= 6:
cursor.execute( "update names set " + kind[row[2] - 1] +
" = %s where name_id = %s",
(row[4], row[1]))
cursor.commit()
connection.clos e()
1) I would prefer "SELECT name_id, part, name FROM name_parts", rather
than relying on * to return the field names in an expected order
and size as your database evolves. I generally do SQL keywords in
all-caps as documentation for those reading the code later.

2) I suspect that last line of the second execute might need to be:
[(row[4], row[1])])
I don't really remember; I'd just try both and see which works.

3) It is not really clear to when you want to do the commits.
I might be tempted to do the first query with "ORDER BY name_id"
and do a commit after each distinct name_id is finished. This
strategy would keep data for individuals coherent.

4) In fact, I'd leave the data in the database. Perhaps more like a
set of queries like:

UPDATE names
SET names.prefix = name_parts.name
FROM name_parts
WHERE names.name_id = name_parts.name _id
AND name_parts.name _kind = 1

You really need to think about commits when you adopt this strategy.

--Scott David Daniels
Sc***********@A cm.Org
Jul 18 '05 #5
In <Gq************ ******@news2.e. nsc.no>, Leif B. Kristensen wrote:
Damjan skrev:
You don't need to escape text when using the Python DB-API.
DB-API will do everything for you.
For example:
SQL = 'INSERT into TEMP data = %s'
c.execute(SQL, """ text containing ' and ` and all other stuff we
might
read from the network""")

You see, the SQL string contains a %s placeholder, but insetad of
executing the simple string expansion SQL % """....""", I call the
execute method with the text as a second *parametar*. Everything else
is magic :).
Sure, but does this work if you need more than one placeholder?


Yes it works with more than one placeholder.
FWIW,
here's the whole script. It will fetch data from the table name_parts
and pump them into the "denormaliz ed" table names ( a real SQL guru
would probably do the same thing with one single monster query):

import psycopg
from re import escape

connection = psycopg.connect ("dbname=slekta ", serialize=0)
sql = connection.curs or()

sql.execute("se lect * from name_parts")
result = sql.fetchall()
for row in result:
if row[2] == 1: # name part = 'prefix'
query = ("update names set prefix='%s' where name_id=%s" % \
(escape(row[4]), row[1]))
elif row[2] == 2: # name part = 'given'
query = ("update names set given='%s' where name_id=%s" % \
(escape(row[4]), row[1]))
elif row[2] == 3: # name part = 'surname'
query = ("update names set surname='%s' where name_id=%s" % \
(escape(row[4]), row[1]))
elif row[2] == 4: # name part = 'suffix'
query = ("update names set suffix='%s' where name_id=%s" % \
(escape(row[4]), row[1]))
elif row[2] == 5: # name part = 'patronym'
query = ("update names set patronym='%s' where name_id=%s" % \
(escape(row[4]), row[1]))
elif row[2] == 6: # name part = 'toponym'
query = ("update names set toponym='%s' where name_id=%s" % \
(escape(row[4]), row[1]))
sql.execute(que ry)
sql.commit()
connection.clos e()


A lot of redundant code. Try something like the following instead of the
``elif`` sequence::

name_part = ['prefix', 'given', 'surname', 'suffix', 'patronym', 'toponym']
for row in result:
query = 'update names set %s=%%s where name_id=%%s' % name_part[row[2]-1]
sql.execute(que ry, (row[4], row[1]))
sql.commit()

Ciao,
Marc 'BlackJack' Rintsch
Jul 18 '05 #6
First, thanks to all who have replied. I learned a lot more than I had
expected :-)

This is a small part of a major project; converting my genealogy
database from a commercial FoxPro application to my homegrown Python /
PostgreSQL app. I'm still in a phase where I'm experimenting with
different models, hence the need for shuffling data between two tables.

Now, the script in its refined form looks like this:

#! /usr/bin/env python
# name_convert.py - populate "names" with values from "name_parts "

import psycopg

name_part = ('prefix','give n','surname','s uffix','patrony m','toponym')
connection = psycopg.connect ("dbname=slekta ", serialize=0)
sql = connection.curs or()
sql.execute("se lect name_id, name_part_type, name_part from name_parts")
result = sql.fetchall()
for row in result:
query = "update names set %s=%%s where name_id=%%s" % \
name_part[row[1]-1]
sql.execute(que ry, (row[2], row[0]))
sql.commit()
connection.clos e()
--
Leif Biberg Kristensen
http://solumslekt.org/
Jul 18 '05 #7
Leif B. Kristensen wrote:
I'm working with a Python program to insert / update textual data into a
PostgreSQL database. The text has single and double quotes in it, and I
wonder: What is the easiest way to escape quotes in Python, similar to
the Perlism "$str =~ s/(['"])/\\$1/g;"?


Just for the record (even though it's not the right solution to your problem), the Python equivalent is
re.sub('''(['"])''', r'\\\1', s)

Kent
Jul 18 '05 #8

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

Similar topics

3
2592
by: TheKeith | last post by:
Hi, I'm just learning php now for the first time and I'm having a little trouble understanding something. In the following example: ------------------------------------------------------------------------ <?php function test ($thenum) {
1
3593
by: JehanNYNJ | last post by:
I have to put some html into a variable like so.... var html = '<TABLE cellspacing="5" border="0" ....... But within this html string I also need to have the code for a button that traps the onclick method like so... ....<input type="button" name="Add Question" value="Repeat Question" onclick="javascript:getQuestion( '3925','38497', '1' )" >....';
4
31238
by: Greg | last post by:
I keep getting an error when I have a tick mark in a text value that I am searching for in my XPath Query. Example: <Authors> <Author LastName="O'Donnel"> <Author LastName="Smith"> </Authors>
12
9644
by: Jeff S | last post by:
In a VB.NET code behind module, I build a string for a link that points to a JavaScript function. The two lines of code below show what is relevant. PopupLink = "javascript:PopUpWindow(" & Chr(34) & PopUpWindowTitle & Chr(34) & ", " & Chr(34) & CurrentEventDetails & ")" strTemp += "<BR><A HREF='#' onClick='" & PopupLink & "'>" & EventName & "</A><BR>" The problem I have is that when the string variables or contain a string with an...
7
4187
by: Axel Dahmen | last post by:
Hi, within a DataGrid control I'm using a DataTable containing a string column to fill a Hyperlink's href attribute. Unfortunately HttpUtility.UrlEncode() doesn't escape the apostroph character, thus ruining some of my hrefs. How do I correctly escape any character using a Page's current encoding (I don't want to hard-code the encoding)? TIA,
131
9272
by: Lawrence D'Oliveiro | last post by:
The "escape" function in the "cgi" module escapes characters with special meanings in HTML. The ones that need escaping are '<', '&' and '"'. However, cgi.escape only escapes the quote character if you pass a second argument of True (the default is False): 'the "quick" &amp; &lt;brown&gt; fox' 'the &quot;quick&quot; &amp; &lt;brown&gt; fox' This seems to me to be dumb. The default option should be the safe one: that is, escape _all_ the potentially troublesome...
8
21481
by: Marina Levit [MVP] | last post by:
I've scoured google, but apparently none of the suggestions actually work. I have the following. type of XPATH query "SomeNode[SomeAttribute = 'abc's search'" Now, I've tried doing this: "SomeNode[SomeAttribute = 'abc@apos;s search'"
10
1921
by: Confused but working on it | last post by:
Hi all, I'm trying to do something simple and grabbed a snippet from the php manual for reading files in a directory. The snippet echos out a nice list of files. <?php //Open images directory $dir = opendir("images"); //List files in images directory while (($file = readdir($dir)) !== false)
1
19313
by: crybaby | last post by:
I wrote a python code in linux text pad and copied to thumb drive and try to ran the file by changing the path to windows: sys.path = sys.path + I get the following error: ValueError: invalid \x escape I am pretty sure this problem is due some kind of linux end of line
0
9563
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
9386
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
10144
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9937
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
9822
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
8821
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2793
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.