How to update a column in SQLite using pysqlite where I first needed to obtain a conditional value from other data in my table?

假如想象 提交于 2019-12-02 20:17:34

问题


So, I have the following issue when updating my database:

I have a column in my table that I need to split in three essentially and so I have the following code:

with con:
  cur = con.cursor()
  cur.execute('SELECT Column1 FROM MainTable')
  while True row = cur.fetchone() 
    if row == None:
      break 
for line in row: a, b, c= line.split('-') 
  print (b);

which gives me the values of the second column for instance. However, I need to UPDATE that second column with those values and for this I have tried adding the following at the bottom:

cur.execute('UPDATE MainTable SET Col_2 = ?' WHERE Id = 1, (row, Id))

con.commit()

However, for some reason this isn't running well.


回答1:


To update a specific row, you need a way to identify the row. You appear to have an "ID" column, so read that together with the string you want split.

SQL statements have nothing to do with Python; what you do in Python is to construct an SQL string that you then give to the database to execute. (Using ?-style parameters avoids string formatting problems and SQL injection attacks; always use them for values.)

cur.execute('SELECT ID, Column1 FROM MainTable')
for id, col1 in cur.fetchall():
    a, b, c = col1.split('-')
    cur.execute('UPDATE MainTable SET ColA = ?, ColB = ?, ColC = ? WHERE ID = ?',
                [a, b, c, id])
con.commit()


来源:https://stackoverflow.com/questions/42074966/how-to-update-a-column-in-sqlite-using-pysqlite-where-i-first-needed-to-obtain-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!