从Python脚本向MySQL表插入数据

13 投票
1 回答
70283 浏览
提问于 2025-04-17 15:49

我有一个名为 TBLTEST 的 MySQL 表,这个表里有两列,分别是 ID 和 qSQL。每个 qSQL 列里存放的是 SQL 查询语句。

我还有另一个表叫 FACTRESTTBL。

在 TBLTEST 表里总共有 10 行数据。

举个例子,假设在 TBLTEST 表中,ID 为 4 的那一行,qSQL 的内容是 "select id, city, state from ABC"。

我想知道如何用 Python 从 TBLTEST 表插入数据到 FACTRESTTBL 表,可能可以用字典来实现?

谢谢!

1 个回答

25

你可以使用MySQLdb这个库来在Python中操作MySQL数据库

下面是一个示例代码(你可能需要自己调试一下,因为我这里无法运行它):

#!/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()

撰写回答