Python SQLITE3 UPDATE给出'None'作为输出

时间:2017-11-30 01:57:11

标签: python database python-3.x sqlite

如果早些时候已经回答了类似的问题,我很抱歉,但我是SQLITE3的初学者(一天之久),我似乎无法理解我在这里做错了什么。

我的表(3列,即{A1,A2,W}):

A1 A2 W
12 67 0
15 01 0

Code:

import sqlite3
import pandas as pd
df = pd.read_csv('/Users/advaitbalaji/Desktop/p.txt', sep = '\t', header = 0)
df.head()
connex = sqlite3.connect('database.db')
cur = connex.cursor()
df.to_sql(name = 'database', con = connex, if_exists = 'replace', index = False)
cur.execute("SELECT Weights FROM database WHERE A1 = 12 AND A2 = 67")
k = cur.fetchone()
print(k)
cur.execute("UPDATE database SET W = W + 1 WHERE A1 = 12 AND 2 = 67")
k = cur.fetchone()
print(k)
connex.commit()


Output:  
 (0,)  
 None

我甚至对代码进行了以下更改,但输出保持不变:

cur.execute("SELECT Weights FROM database WHERE A1 = 12 AND A2 = 67")
k = cur.fetchone()
print(k)
cur.execute("UPDATE database SET W = ? WHERE A1 = 12 AND A2 = 67",(k[0]+1,))
k = cur.fetchone()
print(k)
connex.commit()

Output:
 (0,)
 None

我似乎无法弄清楚为什么我的输出不是如下:

Desired Output:
(0,)
(1,)

1 个答案:

答案 0 :(得分:0)

您正在设置光标以执行更新,要返回结果元组,您需要让光标再次执行选择查询。如果复制与开始时相同的select子句的相同条件,则应返回预期结果。

cur.execute("SELECT W FROM database WHERE A1 = 12 AND A2 = 67")
k = cur.fetchone()
print(k)
cur.execute("UPDATE database SET W = ? WHERE A1 = 12 AND A2 = 67",(k[0]+1,))
cur.execute("SELECT W FROM database WHERE A1 = 12 AND A2 = 67")
k = cur.fetchone()
print(k)