如果行id
为空,如何用Python制作一个脚本来循环该表中的所有行(帐户),并将行name
中的值复制到行name
中?
经过一番阅读,我设法得到了一些代码:
import mysql.connector
db = mysql.connector.connect(
host="localhost",
user="user",
passwd="pass",
database="mydatabase"
)
db_pointer = db.cursor()
db_pointer.execute("SELECT * FROM accounts")
result = db_pointer.fetchall()
for x in result:
print(x)
例如,如何读取每一行中“ email”的值?喜欢:
for x in result:
print(x.email)
预先感谢
答案 0 :(得分:0)
以下代码应为您提供所需的工作示例。
import mysql.connector
db = mysql.connector.connect(
host="localhost",
user="user",
passwd="pass",
database="mydatabase"
)
db_pointer = db.cursor()
db_pointer.execute("SELECT id, ISNULL(name, '') FROM accounts")
result = db_pointer.fetchall()
for x in result:
#assuming that the SELECT query is returned properly x[0] is the id and x[1] is the name
if (x[1] == ""):
#we also assume that id is a primary key
db_pointer2 = db.cursor()
db_pointer2.execute("INSERT INTO accounts SET name = '" + x[0] + "' WHERE id = '" + x[0] + "'")
每个查询结果行都是一个数组,并且使用
访问该数组的每个成员array[index]
方法。