Python 和 SQLite:插入表 [英] Python and SQLite: insert into table

查看:41
本文介绍了Python 和 SQLite:插入表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 3 行的列表,每行代表一个表格行:

<预><代码>>>>打印清单[湖,444,M][锦,445,M][锦,445,M]

如何将这个列表插入到表格中?

我的表结构是:

<前>表名(名称 varchar[100],年龄整数,性别字符 [1])

或者我应该使用列表以外的其他东西吗?

这是实际的代码部分:

 在 self.server 中记录:打印--->",记录t=记录self.cursor.execute("插入服务器(服务器)值(?)",(t[0],));self.cursor.execute("插入服务器(id)值(?)",(t[1],))self.cursor.execute("插入服务器(状态)值(?)",(t[2],));

单独插入三个字段有效,但使用单行

self.cursor.execute("insert into server(server,c_id,status) values (?,?,?)",(t[0],),(t[1],),(t[2],))

self.cursor.execute("insert into server(server,c_id,status) values (?,?,?)",(t),)

没有.

解决方案

conn = sqlite3.connect('/path/to/your/sqlite_file.db')c = conn.cursor()对于 my_list 中的项目:c.execute('插入表名值(?,?,?)', item)

I have a list that has 3 rows each representing a table row:

>>> print list
[laks,444,M]
[kam,445,M]
[kam,445,M]

How to insert this list into a table?

My table structure is:

tablename(name varchar[100], age int, sex char[1])

Or should I use something other than list?

Here is the actual code part:

    for record in self.server:
        print "--->",record
        t=record
        self.cursor.execute("insert into server(server) values (?)",(t[0],));
        self.cursor.execute("insert into server(id) values (?)",(t[1],))
        self.cursor.execute("insert into server(status) values (?)",(t[2],));

Inserting the three fields separately works, but using a single line like

self.cursor.execute("insert into server(server,c_id,status) values (?,?,?)",(t[0],),(t[1],),(t[2],))

or

self.cursor.execute("insert into server(server,c_id,status) values (?,?,?)",(t),)

does not.

解决方案

conn = sqlite3.connect('/path/to/your/sqlite_file.db')
c = conn.cursor()
for item in my_list:
  c.execute('insert into tablename values (?,?,?)', item)

这篇关于Python 和 SQLite:插入表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆