从 Python 脚本将数据插入 MySQL 表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14863692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:41:40  来源:igfitidea点击:

Insert data into MySQL table from Python script

pythonmysql

提问by Mario

I have a MySQL Table named TBLTEST with two columns ID and qSQL. Each qSQL has SQL queries in it.

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

I have another table FACTRESTTBL.

我有另一个表 FACTRESTTBL。

There are 10 rows in the table TBLTEST.

表 TBLTEST 中有 10 行。

For example, On TBLTEST lets take id =4 and qSQL ="select id, city, state from ABC".

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

How can I insert into the FACTRESTTBL from TBLTEST using python, may be using dictionary?

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

Thx!

谢谢!

采纳答案by Leniel Maccaferri

You can use MySQLdb for Python.

您可以将MySQLdb 用于 Python

Sample code (you'll need to debug it as I have no way of running it here):

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

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