[Tutor] sqlite3 lists to database conversion/ using python variables in sqlite3
Kent Johnson
kent37 at tds.net
Wed Nov 19 12:48:41 CET 2008
On Wed, Nov 19, 2008 at 6:18 AM, amit sethi <amit.pureenergy at gmail.com> wrote:
>>>> list1=['hello','hi']
>>>> list2=['a','b']
>>>>c.execute('''create table ABC(hello text,hi text)''')
>>>> list1_value= ",".join(list1)
>>>> list2_value= ",".join(list2)
>>>> c.execute('''insert into ABC (%s) values
>>>> (%s)''')%(list1_value,list2_value)
The parenthesis are in the wrong place to do what you intend, and the
double quotes are not needed. But this is not the right way to do it.
You should pass the values separately, not in the sql string. This
allows the database program to correctly escape values containing
special characters such as quote or comma, and it prevents sql
injection attacks. There is probably no reason to put the field names
in a list. Try this:
c.execute('insert into ABC hello, hi values ?, ?', list2)
Notice that list2 is passed as a parameter to execute.
Kent
More information about the Tutor
mailing list