473,386 Members | 1,799 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,386 software developers and data experts.

insert a dictionary into sql data base

I have a dictionary that contains a row of data intended for a data base.

The dictionary keys are the field names. The values are the values to be
inserted.

I am looking for a good pythonic way of expressing this, but I have a
problem with the way lists are represented when converted to strings.

Lets say my dictionary is

data = {"fname": "todd", "lname": "Bush"}
fields = data.keys()
vals = []
for v in fields:
vals.append(data[v])

sql = """INSERT INTO table (%s) VALUES (%s);""" % (fields, vals)

but fields and vals are represented as lists. So, then I need to strip the
[] from them, but then ... there must be an easier way.

Any advise?

--
David Bear
-- let me buy your intellectual property, I want to own your thoughts --
Dec 5 '05 #1
7 20881
David Bear wrote:
The dictionary keys are the field names. The values are the values to be
inserted.

I am looking for a good pythonic way of expressing this, but I have a
problem with the way lists are represented when converted to strings.

Lets say my dictionary is

data = {"fname": "todd", "lname": "Bush"}
fields = data.keys()
vals = []
for v in fields:
vals.append(data[v])

sql = """INSERT INTO table (%s) VALUES (%s);""" % (fields, vals)

but fields and vals are represented as lists. So, then I need to strip the
[] from them, but then ... there must be an easier way.

Any advise?


1) use parameters to pass in the values (see
http://www.python.org/peps/pep-0249.html )

2) use parameters to pass in values

3) use parameters to pass in values

4) here's a simplified version of your code:

data = {"fname": "todd", "lname": "Bush"}

fields = data.keys()
values = data.values()

cursor.execute(
"INSERT INTO table (%s) VALUES (%%s);" % (",".join(fields)),
*values
)

(this assumes that your database uses %s for parameters; if it uses
? instead, replace "%%s" with "?". see the paramstyle documentation
in the db-api docs (pep 249) for more info)

</F>

Dec 5 '05 #2
Fredrik Lundh wrote:
cursor.execute(
"INSERT INTO table (%s) VALUES (%%s);" % (",".join(fields)),
*values
)


Thanks for the hint. However, I don't understand the syntax.

I will be inserting in to postgresql 8.x. I assumed the entire string would
be evaluated prior to being sent to the cursor. However, when I attempt to
manual construct the sql insert statment above I get an error:
print "INSERT INTO table (%s) VALUES (%%s);" % (",".join(fields),

*values)
File "<stdin>", line 1
print "INSERT INTO table (%s) VALUES (%%s);" % (",".join(fields),
*values)
^
SyntaxError: invalid syntax
--
David Bear
-- let me buy your intellectual property, I want to own your thoughts --
Dec 5 '05 #3
David Bear wrote
Fredrik Lundh wrote:
cursor.execute(
"INSERT INTO table (%s) VALUES (%%s);" % (",".join(fields)),
*values
)
Thanks for the hint. However, I don't understand the syntax.

I will be inserting in to postgresql 8.x. I assumed the entire string would
be evaluated prior to being sent to the cursor.


Looks like you missed advice 1-3. I'll take it again: DON'T USE STRING
FORMATTING TO INSERT VALUES IN A DATABASE. Sorry for shouting,
but this is important. Parameter passing gives you simpler code, and
fewer security holes.
However, when I attempt to manual construct the sql insert statment
above I get an error:
print "INSERT INTO table (%s) VALUES (%%s);" % (",".join(fields),

*values)
File "<stdin>", line 1
print "INSERT INTO table (%s) VALUES (%%s);" % (",".join(fields),
*values)
^
SyntaxError: invalid syntax


DON'T MANUALLY CONSTRUCT THE SQL INSERT STATEMENT. Use string
formatting to insert the field names, but let the database layer deal with
the values.

If you want to do things in two steps, do the fields formatting first

query = "INSERT INTO table (%s) VALUES (%%s);" % (",".join(fields))

and pass the query and the values sequence to the database layer:

cursor.execute(query, values)

The database will take care of the rest.

</F>

Dec 5 '05 #4
Fredrik Lundh wrote:
David Bear wrote
Fredrik Lundh wrote:
> cursor.execute(
> "INSERT INTO table (%s) VALUES (%%s);" % (",".join(fields)),
> *values
> )
Thanks for the hint. However, I don't understand the syntax.

I will be inserting in to postgresql 8.x. I assumed the entire string
would be evaluated prior to being sent to the cursor.


Looks like you missed advice 1-3. I'll take it again: DON'T USE STRING
FORMATTING TO INSERT VALUES IN A DATABASE. Sorry for shouting,
but this is important. Parameter passing gives you simpler code, and
fewer security holes.


please, shout until I 'get it'... I don't mind. I just don't understand
using the star in front of the values variable; it generates a syntax
exception for me.
However, when I attempt to manual construct the sql insert statment
above I get an error:
>>> print "INSERT INTO table (%s) VALUES (%%s);" % (",".join(fields),

*values)
File "<stdin>", line 1
print "INSERT INTO table (%s) VALUES (%%s);" % (",".join(fields),
*values)
^
SyntaxError: invalid syntax


DON'T MANUALLY CONSTRUCT THE SQL INSERT STATEMENT. Use string
formatting to insert the field names, but let the database layer deal with
the values.


since I am so new to this, I didn't know the database layer would handle
this for me. Is the evaluation of the fieldname done by the dbapi layer or
by postgresql?
If you want to do things in two steps, do the fields formatting first

query = "INSERT INTO table (%s) VALUES (%%s);" % (",".join(fields))

and pass the query and the values sequence to the database layer:

cursor.execute(query, values)
I found this info on the pgdb interface:

http://www.pygresql.org/pg.html

section 4.7 describes the insert method. It is passed the tablename and a
dictionary. But it doesn't describe how it resolves fieldnames and their
values. I assume the dictionary key MUST correspond to a named field.

The database will take care of the rest.
this is my trouble. I always think I need to do more -- but I can't seem to
find good examples on the http://www.pygresql.org/pgdb.html website.

Do know of any good examples?

</F>


--
David Bear
-- let me buy your intellectual property, I want to own your thoughts --
Dec 5 '05 #5
Fredrik Lundh wrote:
David Bear wrote
Fredrik Lundh wrote:
> cursor.execute(
> "INSERT INTO table (%s) VALUES (%%s);" % (",".join(fields)),
> *values
> )


Thanks for the hint. However, I don't understand the syntax.

I will be inserting in to postgresql 8.x. I assumed the entire string
would be evaluated prior to being sent to the cursor.


Looks like you missed advice 1-3. I'll take it again: DON'T USE STRING
FORMATTING TO INSERT VALUES IN A DATABASE. Sorry for shouting,
but this is important. Parameter passing gives you simpler code, and
fewer security holes.
However, when I attempt to manual construct the sql insert statment
above I get an error:
>>> print "INSERT INTO table (%s) VALUES (%%s);" % (",".join(fields),

*values)
File "<stdin>", line 1
print "INSERT INTO table (%s) VALUES (%%s);" % (",".join(fields),
*values)
^
SyntaxError: invalid syntax


DON'T MANUALLY CONSTRUCT THE SQL INSERT STATEMENT. Use string
formatting to insert the field names, but let the database layer deal with
the values.

If you want to do things in two steps, do the fields formatting first

query = "INSERT INTO table (%s) VALUES (%%s);" % (",".join(fields))

and pass the query and the values sequence to the database layer:

cursor.execute(query, values)

The database will take care of the rest.

</F>


I think I'm missing some important documentation somewhere. Here's what I
tried (using both % and $ signs):
sql 'INSERT INTO nic (addr_code,ip_address,property_control,mac_address ) VALUES
(%s);'
sql2 'INSERT INTO nic (addr_code,ip_address,property_control,mac_address ) VALUES
($s);' values ['p', '129.219.120.134', '6154856', '00:40:50:60:03:02']
cursor.execute(sql1, values) Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'sql1' is not defined cursor.execute(sql, values)

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib64/python2.4/site-packages/pgdb.py", line 163, in execute
self.executemany(operation, (params,))
File "/usr/lib64/python2.4/site-packages/pgdb.py", line 187, in
executemany
raise OperationalError, "internal error in '%s': %s" % (sql,err)
pg.OperationalError: internal error in 'INIT': not all arguments converted
during string formatting

I get the same error if using $ sign.

When I look at the pygresql dbapi official site at
http://www.pygresql.org/pgdb.html

"this section needs to be written"...

I would really appreciate some more examples on using pgdb (pygresql)
--
David Bear
-- let me buy your intellectual property, I want to own your thoughts --
Dec 6 '05 #6
On Mon, 05 Dec 2005 18:00:21 -0700, David Bear wrote
Fredrik Lundh wrote:
DON'T MANUALLY CONSTRUCT THE SQL INSERT STATEMENT. Use string
formatting to insert the field names, but let the database layer deal with
the values.

If you want to do things in two steps, do the fields formatting first

query = "INSERT INTO table (%s) VALUES (%%s);" % (",".join(fields))

and pass the query and the values sequence to the database layer:

cursor.execute(query, values)

The database will take care of the rest.

</F>


I think I'm missing some important documentation somewhere. Here's
what I tried (using both % and $ signs):
sql 'INSERT INTO nic (addr_code,ip_address,property_control,mac_address )
VALUES
(%s);'
sql2 'INSERT INTO nic (addr_code,ip_address,property_control,mac_address )
VALUES
($s);' values ['p', '129.219.120.134', '6154856', '00:40:50:60:03:02']
cursor.execute(sql1, values) Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'sql1' is not defined cursor.execute(sql, values)

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib64/python2.4/site-packages/pgdb.py", line 163, in execute
self.executemany(operation, (params,))
File "/usr/lib64/python2.4/site-packages/pgdb.py", line 187, in
executemany
raise OperationalError, "internal error in '%s': %s" % (sql,err)
pg.OperationalError: internal error in 'INIT': not all arguments converted
during string formatting

I get the same error if using $ sign.

When I look at the pygresql dbapi official site at
http://www.pygresql.org/pgdb.html

"this section needs to be written"...

I would really appreciate some more examples on using pgdb (pygresql)


It appears that Fredrik gave you good advice but bad example code. The example
he gave you constructs an insert query with only one parameter placeholder.
You'll need as many placeholders as the number of values that are inserted.

The following example should work better:

def insertDict(curs, tablename, data):
fields = data.keys()
values = data.values()
placeholder = "%s"
fieldlist = ",".join(fields)
placeholderlist = ",".join([placeholder] * len(fields))
query = "insert into %s(%s) values (%s)" % (tablename, fieldlist,
placeholderlist)
curs.execute(query, values)

The main thing to note here is that we *are* using string formatting to build
a query that's based on a variable table name and a variable column list, but
we *are not* using string formatting to fill in the values.[*]

On a somewhat related note, it's unfortunate that many database modules use %s
as parameter placeholders, because it makes it too tempting to write bad code
such as

cur.execute("insert into tab1(spam,eggs) values (%s,%s)" % (a,b)) # Bad, uses
vulnerable and error-prone string formatting

instead of

cur.execute("insert into tab1(spam,eggs) values (%s,%s)", (a,b)) # Good, uses
parameters.
[*] This code blindly trusts that the table name and dictionary keys don't
contain SQL injection attacks. If the source of these is not completely
trustworthy, the code needs to be hardened against such attacks. I'll leave
that as an exercise for the reader.

Hope this helps,

Carsten.

Dec 6 '05 #7
Carsten Haese wrote:
The
example he gave you constructs an insert query with only one parameter
placeholder. You'll need as many placeholders as the number of values that
are inserted.

The following example should work better:

def insertDict(curs, tablename, data):
fields = data.keys()
values = data.values()
placeholder = "%s"
fieldlist = ",".join(fields)
placeholderlist = ",".join([placeholder] * len(fields))
query = "insert into %s(%s) values (%s)" % (tablename, fieldlist,
placeholderlist)
curs.execute(query, values)

The main thing to note here is that we *are* using string formatting to
build a query that's based on a variable table name and a variable column
list, but we *are not* using string formatting to fill in the values.[*]

On a somewhat related note, it's unfortunate that many database modules
use %s
as parameter placeholders, because it makes it too tempting to write bad
code
such as

cur.execute("insert into tab1(spam,eggs) values (%s,%s)" % (a,b)) # Bad,
uses vulnerable and error-prone string formatting

instead of

cur.execute("insert into tab1(spam,eggs) values (%s,%s)", (a,b)) # Good,
uses parameters.

[*] This code blindly trusts that the table name and dictionary keys don't
contain SQL injection attacks. If the source of these is not completely
trustworthy, the code needs to be hardened against such attacks. I'll
leave that as an exercise for the reader.

Hope this helps,

Carsten.


Thank you very much for the greater explanation. Yes, I was not
understanding that that %s in one instance was a python string format
operator, and in another instance it was a placeholder sent to the dbapi
objects (and I supposed on down into the data base cursor) for the
parameters following the function call. BIG DIFFERENCE.

--
David Bear
-- let me buy your intellectual property, I want to own your thoughts --
Dec 6 '05 #8

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

Similar topics

1
by: N i E ¶ W i A D o M y | last post by:
Hello. I have a problem with insert a picture (bmp) to data base. I wan't add picture to cell in data base (Access) like double decimal. Someone have a idea how to make this? Please help ...
2
by: gaston | last post by:
Hi All I have three data bases with a table each one, what I want to do is to get the data from each table and insert it in a new data base table. The thing is that may be there is going to a...
8
by: slb813 | last post by:
Hello, I am having a problem that I can't seem to work out. I am running Apache 2.2 on a Windows XP platform, using PHP5. I am attempting to insert a row into a MS Access data base with a PHP...
0
by: twilight lover | last post by:
i write a small prog with builder c++ 5 that extract lines from text file then add them into Paradoxe7 table these lines will appear in a DBGrid on the Form by a click on Button1 the file contains...
1
by: vaskarbasak | last post by:
Hi friends, I have a 500 zip file. I am trying to read the zip file .Then insert the data in to DB .But it is taking long time. I have to insert all record into DB with in 1 hr. please help...
13
by: deepunarayan | last post by:
Hi I have Problem in ASP. I have created a Multi choice Question page in ASP with Submit button. When I submit my page the User Selected values will be taken to the other page where validation...
0
by: Sabzar | last post by:
Hi every buddy.. i need to store resume in mysql data base and also retrieve to display it in jsp page .what the data type should i use for database. i tried it as a blob type. and in action class...
0
Vkas
by: Vkas | last post by:
I have a default .aspx form i HAVE 3 TEXT BOX 1 DROPDOWN LIST IN MY DEFAULT PAGE. a access data base file at locaion C:\asp.netdb\feedback.accdb I want to insert the values into the access...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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?
0
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...
0
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,...
0
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...

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.