如何更新 SQL 数据库中的值?SQLite/Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22872814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:51:15  来源:igfitidea点击:

How do i update values in an SQL database? SQLite/Python

pythonsqlsqlite

提问by Hamzah Akhtar

I have created a table, and have inserted data into the table. I wanted to know how I could update/edit the data. For example, if I have multiple columns in the table, of which one is named 'age' and the data for the column is = '17', and I now wanted to replace '17' with '18', would I do the following?

我创建了一个表,并将数据插入到表中。我想知道如何更新/编辑数据。例如,如果我在表中有多个列,其中一个列名为“age”,列的数据为 = '17',而我现在想用 '18' 替换 '17',我会这样做吗?下列的?

import sqlite3 as lite
import sys

con = lite.connect('Records.db')

with con:
    cur = con.cursor()    
    cur.execute("INSERT INTO ExampleTable(Age) VALUES(18) WHERE (Age = 17)")

采纳答案by Gyan Veda

To update values in a SQL database using the SQLite library in Python, use a statement like this one.

要使用 Python 中的 SQLite 库更新 SQL 数据库中的值,请使用这样的语句。

cur.execute("UPDATE ExampleTable SET Age = 18 WHERE Age = 17")

cur.execute("UPDATE ExampleTable SET Age = 18 WHERE Age = 17")

For a great introduction to using SQLite in Python, see this tutorial.

有关在 Python 中使用 SQLite 的精彩介绍,请参阅本教程

回答by Micha? Staniewski

I'm not into Python, but i think i can help, so

我不喜欢 Python,但我想我可以提供帮助,所以

cur.execute("UPDATE ExampleTable SET age = 18 WHERE age = 17")

If i'm wrong, sorry then

如果我错了,那么对不起

回答by Hamzah Akhtar

with con:
    cur = con.cursor()
    cur.execute("UPDATE Table_Name SET Age='18' WHERE Age='17'")

回答by Tazz

In sqlite3 with Python3.x works to me something like this:

在带有 Python3.x 的 sqlite3 对我来说是这样的:

newPrice = '.99'
book_id = 4
cursor.execute('''UPDATE books SET price = ? WHERE id = ?''', (newPrice, book_id))