python在列表中添加列表,使用python在特定列中插入列表

i have a database where there are two column sess_id and data. Now i want to insert a list from py to db how should i do this.

suppose this is the list to be inserted in data column of list.

database_list= ['elem1','elem2','elem3'...]

this is what in have done but no progress:

cursor_three=conn.cursor()

cursor_three.execute('INSERT INTO table (data) VALUES (database_list)')

cursor_three.commit()

解决方案

You should iterate list like this:

cursor_three=conn.cursor()

for elem in database_list:

cursor_three.execute('INSERT INTO table (data) VALUES (%s)' % elem)

cursor_three.commit()

After that you will have sess_id column empty unless you declared it autoincrement row. If you have two sorted arrays for example

database_id_list = [212, 444, 532...]

database_data_list= ['elem212','elem444','elem532'...]

You should use zip() function to iterate them simulteniously, like this:

for elem in zip(database_id_list, database_data_list):

cursor_three.execute('INSERT INTO table (sess_id, data) VALUES (%s, %s)' % elem) # elem is tuple here

Notice that this code is using string fromat function for simplness (you didn't noticed which database you're using) and it is not protected from SQL injections. You better use your sql deriver's formatter, for example for psycopg2:

cursor_three.execute('INSERT INTO table (data) VALUES (%s)', [elem])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值