您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

从Python脚本将数据插入MySQL表

从Python脚本将数据插入MySQL表

您可以将MySQLdb用于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()
MySQL 2022/1/1 18:49:11 有345人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶