循环数据库行并将字段复制到另一个字段

时间:2019-03-28 19:21:25

标签: python

MySQL数据库表“帐户” My database example

如果行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)

预先感谢

1 个答案:

答案 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]

方法。