【问题标题】:Insert data into MySQL table from Python script从 Python 脚本将数据插入 MySQL 表
【发布时间】:2020-11-27 21:33:49
【问题描述】:

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

我有另一个表 FACTRESTTBL。

表 TBLTEST 中有 10 行。

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

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

谢谢!

【问题讨论】:

  • 您想在qSQL 列执行查询并将结果插入FACTRESTTBLFACTRESTTBL的列是什么?
  • FACTRESTTBL 中的列是 id, city

标签: python mysql


【解决方案1】:

您可以使用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()

【讨论】:

  • 还有github.com/petehunt/PyMySQL,如果这对于分发目的很重要的话,它就是纯python。
  • 给定查询有效。由于 TBLTEST 中有 10 行及以上的查询运行,如果我尝试一次执行 1 个查询。我想执行多个查询,比如: cursor.execute("SELECT qSQL FROM TBLTEST WHERE id in(4, 5, 6)"), for id=5, qSQL="select id, city, zip from DEF" for id =6, qSQL="select id, city, County from ABC" 你会怎么做呢?谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-22
  • 1970-01-01
相关资源
最近更新 更多