使用Python和Sqlite3 如何从sqlite中获取值,将其存储在变量中,然后向其中添加一个字符串并更新它?
import sqlite3
connection = sqlite3.connect("intel.db")
database = connection.cursor()
u = 'Zero'
all = database.execute("SELECT * FROM logs")
newtext = ' message.content '
for w in all:
if u in w[1]:
print("exist")
olddata = database.execute("SELECT logtext FROM logs where loguser=? ", (u))
## use olddata + newtext then add to updated
updated = database.execute("UPDATE logs SET logtext = ? WHERE loguser = ?", (olddata + newtext, u,))
print("User textlog updated")
break
答案 0 :(得分:0)
是的,你可以,但你需要知道正确的语法,下面我创建了一个新的数据库,并插入两个记录数据,然后从db获取值并更新它:
import sqlite3
conn = sqlite3.connect('intel.db')
database = conn.cursor()
database.execute('''CREATE TABLE logs
(date text, logtext text, loguser text, qty real, price real)''')
# Insert a row of data
database.execute("INSERT INTO logs VALUES ('2006-01-05','HI','Zero',100,35.14)")
database.execute("INSERT INTO logs VALUES ('2006-01-03','HELLO','David',100,35.14)")
# Save (commit) the changes
conn.commit()
u = 'Zero'
all_data = database.execute("SELECT * FROM logs")
newtext = ' message.content '
for w in all_data:
if u in w:
print("exist")
olddata = database.execute("SELECT logtext FROM logs where loguser=? ", (u,)).fetchone()[0]
print "Old Data:"
print olddata
database.execute("UPDATE logs SET logtext = ? WHERE loguser = ?", (olddata + newtext, u,))
conn.commit()
newdata = database.execute("SELECT * FROM logs where loguser=? ", (u,)).fetchone()
print "New Data:"
print newdata
conn.close()
输出将是:
exist
Old Data:
HI
New Data:
(u'2006-01-05', u'HI message.content ', u'Zero', 100.0, 35.14)
如您所见,HI
已使用新数据HI message.content
进行了更新。