从Python脚本将数据插入MySQL表

发布于 2021-01-29 15:26:20

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

我有另一个表FACTRESTTBL。

表TBLTEST中有10行。

例如,在TBLTEST上,让id = 4,qSQL =“从ABC选择ID,城市,州”。

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

谢谢!

关注者
0
被浏览
49
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看