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

前端 未结 1 1624
[愿得一人]
[愿得一人] 2021-01-26 07:26

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:

<
相关标签:
1条回答
  • 2021-01-26 07:53

    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()
    
    0 讨论(0)
提交回复
热议问题