来自 MySQL 数据库的 Select 数据,并使用 Python 使其成为一个值

Select data from MySQL database and make it a value using Python

我正在使用 Python 2.7 和 mysqldb。我创建了一个名为 table1 的 table,它有两个字段 (id, id2)。

-id field
-234
-490
-678
-566
-569

-id2 field
-10
-29
-78
-46
-59

我想要一个脚本来使行的 id2 成为一个变量(值),以便通过电子邮件发送或打印它。我希望它成为一个值有一个特定的原因。例如,我想 select id=678 的行,并自动获取该行的 id2 作为变量,我可以在脚本的其他行中使用该变量。

使用execute到运行一个MySQLSELECT命令:

db.execute("SELECT id2 from my_table where id = '%s';" % user)

(用户是您要 select 来自的 id)

编辑:是的,您需要跟进data = cursor.fetchall()

db.execute("SELECT id2 from my_table where id='{0}';".format(user))
ids = [i[0][0] if i else None for i in cursor.fetchall()]