2014-01-15 38 views
0

我第一次使用sqlite。我之前使用过Xammp。现在我在这里有一个场景。每次运行下面的代码时,记录都不会附加在表的末尾,而是表被创建为新的,因此它就像控制台一样工作。为什么记录没有保存在sqlite3中?

任何人都可以告诉我我在做什么错吗?

import sqlite3 

db = sqlite3.connect('test.db') 
db.row_factory = sqlite3.Row 

db.execute('drop table if exists test') 
db.execute('create table test (t1 text,i1 text)') 
db.execute('insert into test (t1, i1) values (?, ?)',('xyzs','51')) 
cursor = db.execute('select * from test') 

for row in cursor: 
    print(row['t1'],row['i1']) 
+0

那我该怎么办? @ user2864740 – Nabin

回答

1

首先,您需要在光标上执行命令,而不是连接本身。其次,您需要承诺您的交易:

import sqlite3 

db = sqlite3.connect('test.db') 
db.row_factory = sqlite3.Row 
cur = db.cursor() # getting a cursor 

cur.execute('drop table if exists test') 
cur.execute('create table test (t1 text,i1 text)') 
db.commit() # commit the transaction, note commits are done 
      # at the connection, not on the cursor 

cur.execute('insert into test (t1, i1) values (?, ?)',('xyzs','51')) 
db.commit() 

cursor = cur.execute('select * from test') 

for row in cursor: 
    print(row['t1'],row['i1']) 

请看看documentation。这将帮助您在开始使用Python中的其他数据库时使用它们,因为它们都遵循相同的API。

+0

如果我运行这段代码两次,我会得到两条记录吗? @Burhan – Nabin

+0

你可以在连接上调用'execute'(http://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.execute) –

+0

谢谢!它的工作... – Nabin

1

这条线将删除旧表:

db.execute('drop table if exists test') 

而这一次创建一个新表:

db.execute('create table test (t1 text,i1 text)') 

这应该解释一下你的问题。删除这两行,你会没事的 - 但首先分别创建表

+0

我评论了这两行。但是同样的问题.. – Nabin

+0

完全一样的问题? – aIKid

相关问题