Skip to content Skip to sidebar Skip to footer

Insert Data Into Mysql Table From Python Script

I have a MySQL Table named TBLTEST with two columns ID and qSQL. Each qSQL has SQL queries in it. I have another table FACTRESTTBL. There are 10 rows in the table TBLTEST. For exam

Solution 1:

You can use MySQLdb for Python.

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

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

Post a Comment for "Insert Data Into Mysql Table From Python Script"