我如何使用我的sqlite3数据库中的表数据作为python变量

时间:2011-05-02 06:44:51

标签: python database sqlite

到目前为止我的代码

conn = sqlite3.connect('databaserm/database')      
curs = conn.cursor()         
curs.execute('SELECT * FROM saves')     
lvl = curs.fetchone()    
conn.close()

ok maybes它用于将数据添加到db

的代码

我试过这个

cn = sqlite3.connect(/databaserm/database")
curs = cn.cursor()
curs.execute('DROP TABLE saves')
curs.execute('CREATE TABLE saves (lvl)')
#curs.execute('INSERT INTO saves VALUES (null, ?)', lvl)

query = """INSERT INTO saves (lvl)
                VALUES (?)"""
data =  [lvl]

curs.execute(query, data)

cn.commit
cn.close()

和这个

conn = sqlite3.connect('/databaserm/database')
curs = conn.cursor()
curs.execute('INSERT INTO saves VALUES(null, ?,)', (lvl,))
conn.commit

1 个答案:

答案 0 :(得分:0)

执行select然后fetchone将返回元组。你还需要什么?

以下是一个例子:

import sqlite3 as sqlite

con = sqlite.connect(':memory:')
cursor = con.cursor()

cursor.execute('''
    create table names (id integer primary key,
                        name varchar(50), email varchar(50))''')

cursor.execute('''
    insert into names values (null, "John Doe", "jdoe@jdoe.zz")''')
cursor.execute('''
    insert into names values (null, "Mary Sue", "msue@msue.yy")''')

name = """Lu'k'e d"fdf" Sma"""
email = "use@force.net"

cursor.execute(
    '''insert into names values (null, ?, ?)''',
    (name, email))

cursor.execute('select * from names')

for c in cursor:
    print c

使用cursor上的迭代(获取结果的另一种方法)。打印:

(1, u'John Doe', u'jdoe@jdoe.zz')
(2, u'Mary Sue', u'msue@msue.yy')
(3, u'Lu\'k\'e d"fdf" Sma', u'use@force.net')

使用fetchone代替迭代:

print cursor.fetchone()
cursor.close()

打印:

(1, u'John Doe', u'jdoe@jdoe.zz')