gpt4 book ai didi

python - 从 Python 脚本将数据插入 MySQL 表

转载 作者:IT老高 更新时间:2023-10-29 00:10:37 28 4
gpt4 key购买 nike

我有一个名为 TBLTEST 的 MySQL 表,其中包含两列 ID 和 qSQL。每个 qSQL 中都有 SQL 查询。

我有另一个表 FACTRESTTBL。

表 TBLTEST 中有 10 行。

例如,在 TBLTEST 上让 id =4 和 qSQL ="select id, city, state from ABC"。

我如何使用 python 从 TBLTEST 插入到 FACTRESTTBL,可能正在使用字典?

谢谢!

最佳答案

您可以使用 MySQLdb for Python .

示例代码(您需要调试它,因为我无法在此处运行它):

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Select qSQL with id=4.
cursor.execute("SELECT qSQL FROM TBLTEST WHERE id = 4")

# Fetch a single row using fetchone() method.
results = cursor.fetchone()

qSQL = results[0]

cursor.execute(qSQL)

# Fetch all the rows in a list of lists.
qSQLresults = cursor.fetchall()
for row in qSQLresults:
id = row[0]
city = row[1]

#SQL query to INSERT a record into the table FACTRESTTBL.
cursor.execute('''INSERT into FACTRESTTBL (id, city)
values (%s, %s)''',
(id, city))

# Commit your changes in the database
db.commit()

# disconnect from server
db.close()

关于python - 从 Python 脚本将数据插入 MySQL 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14863692/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com