Re: passing list values to an executemany cursor
Federico Di Gregorio <fog-NGVKUo/i/[email protected]>
| Newsgroups | gmane.comp.python.db.psycopg.devel |
|---|---|
| Organization | initd.org |
| Message-ID | <1250679583.4299.8.camel@mila> |
Il giorno mar, 18/08/2009 alle 17.47 -0700, Peter Tittmann ha scritto:
[snip]
> insert_st='INSERT INTO pmh VALUES ('+frcs_o+')'
> cur.executemany(insert_st)
>
> con.commit()
>
>
> The result is as follows:
> >>> {'pmh_chainsaw': 84.031250000000014, 'pmh_loaderb':
> 155.75707692307691, 'pmh_truck': 93.977430555555571, 'pmh_loaders':
> 126.94655384615383}
> Traceback (most recent call last):
> File "/tmp/py4195FHt", line 38, in <module>
> insert_st='INSERT INTO pmh VALUES ('+frcs_o+')'
> TypeError: cannot concatenate 'str' and 'list' objects
This is a Python error, nothing related to psycopg. You're trying to
concatenate two strings and a list. Also this seems a simple INSERT to
me, why are you using executemany()?
> It appears that the connection is working and the lists have been
> populated. I can check the db and see that the table has been created
> with the appropriate column names. Any hints on correctly passing the
> list falues from the 'frcs_o' list would be most gratefully recieved.
Supposing frcs_o contains a single row of values you can do :
insert_st = "INSERT INTO pmh VALUES (" + \
",".join(["%s"]*len(frcs_names)) + ")"
cur.execute(insert_st, tuple(frcs_o))
The tricky part just generate the correct number of place holders for
the query statement. If, for example, len(frcs_names) is 3 you'll get:
INSERT INTO pmh VALUES (%s,%s,%s)
If and only if frcs_o is a list of tuples you can use executemany() to
insert more than one row at a time:
cur.executemany(insert_st, frcs_o)
Hope this helps,
federico
--
Federico Di Gregorio http://people.initd.org/fog
Debian GNU/Linux Developer [email protected]
INIT.D Developer fog-NGVKUo/i/[email protected]
Spesso crescere ed andare a vivere da soli è l'unico modo di restare
bambini. -- Alice Fontana
_______________________________________________
Psycopg mailing list
Psycopg-IAPFreCvJWPBWskQ1e/[email protected]
http://lists.initd.org/mailman/listinfo/psycopg
signature.asc
(application/pgp-signature, 197 B)
-----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEABECAAYFAkqL2xkACgkQvcCgrgZGjeuV9wCfZHyTuKZ7DFJlqqYz9tQ7svds ow4Anihks9B05X3RYp5x9EcrZ68F2Ek5 =61yx -----END PGP SIGNATURE-----