Python SQLite3更新不更新的地方

2024-09-22 16:29:45 发布

您现在位置:Python中文网/ 问答频道 /正文

问题:调用我的方法,值会被执行并应该被提交,但不会。下面的方法,但不会生成任何错误。。。什么都不会发生,但会打印值:

def updateNameWhereTime(self, time, name): # time is a floating point from time.time(), 
                                           # name is a simple string like 'this'
    print(time, name) # This prints right values.
    self.db.execute("UPDATE Flights SET name=(?) WHERE startTime=(?);", (name, time))
    self.db.commit() # Does not save anything to the .db

我可以隔离的数据库,我可以完美的。(quarantine here)。我知道这个代码应该运行。另外,我是个初学者,这是我的第一个项目。在

有什么我应该找的吗?有什么事我可能不做吗?在

编辑:在这里生成数据的完整代码,具有用于测试运行的静态示例html:https://github.com/SimonWoodburyForget/Experiments/tree/master/WarThunder


Tags: 方法代码namefromselfdbstringtime
2条回答

如果希望将startTime存储为日期或时间戳,则需要在创建时相应地声明列的数据类型。在

c.execute("create table Flights (..., startTime date or startTime timestamp, ...)")

注意,sqlite内部不会将数据存储为日期或时间戳。数据将是数字。在

挑战的一部分是确保update语句中的数据类型与将数据插入表中时使用的数据类型匹配。在

如果您决定以这种方式创建startTime列,那么缺省适配器就足以满足您的需要。下面是指向文档的链接,紧跟在最相关的示例代码之后。在

https://docs.python.org/2/library/sqlite3.html#sqlite3.PARSE_COLNAMES

^{pr2}$

下面是以时间为文本的示例代码。它又快又脏,所以你可以用它来测试。我会把它转换成时间。时间(). 在

如果startType函数参数的数据类型与数据库startTime数据类型不匹配,这当然也是一个问题,并且不会找到匹配项来更新。在

def updateNameWhereTime(time, name): # time is a floating point from time.time(),                        
    print(time, name) 
    c.execute("UPDATE Flights SET name=? WHERE startTime=?;", (name, time))
    conn.commit() 

def insertRows(table, startTime, name):
    c.execute("INSERT INTO Flights VALUES ('"+startTime+"', '"+name+"')")

def printTableRows(table):
    for row in c.execute("SELECT * FROM "+table):
        print row

import sqlite3
conn = sqlite3.connect('example.db')

c = conn.cursor()

c.execute('''DROP TABLE IF EXISTS Flights''')
c.execute('''CREATE TABLE Flights
             (startTime text, name text)''')

print "Inserting rows into table"
insertRows('Flights','2015-04-11 10:00','Test 1')
insertRows('Flights','2015-04-11 10:05','Test 2')
insertRows('Flights','2015-04-11 10:10','Test 3')
insertRows('Flights','2015-04-11 10:15','Test 4')

print "Original data in table"
printTableRows('Flights')

print "Updating rows in table"
updateNameWhereTime('2015-04-11 10:05','Test 2 Updated')
updateNameWhereTime('2015-04-11 10:10','Test 3 Updated')

print "Updated rows in table"
printTableRows('Flights')

以下是生成的输出:

^{pr2}$

相关问题 更多 >