简体   繁体   中英

Inserting mysql data from one table to another with python

I'm trying to insert data that's already in one mysql table into another, using python. The column names are the same in each table, and objkey is the distinguishing piece of data I have for the item that I'd like to use to tell mysql which columns to look at.

import MySQLdb

db = MySQLdb.connect(host='', user='', passwd='', db='')
cursor = db.cursor

sql = "INSERT INTO newtable (%s, %s, %s, %s) SELECT %s, %s, %s, %s FROM oldtable
WHERE %s;" % ((name, desig, data, num), name, desig, data, num, obj = repr(objkey))
cursor.execute(sql)

db.commit()
db.close()

It says I have a syntax error, but I'm not sure where since I'm pretty sure there should be parentheses around the field names the first time but not the second one. Anyone know what I'm doing wrong?

I'm not exactly sure what you are trying to do with the obj = repr(objkey) line, but python is thinking you are defining variables with this line, not setting sql syntax (if that is indeed your desire here).

sql = "INSERT INTO newtable (%s, %s, %s, %s) SELECT %s, %s, %s, %s FROM oldtable 
WHERE %s;" % ((name, desig, data, num), name, desig, data, num, obj = repr(objkey))

should probably be changed to something like:

sql = "INSERT INTO newtable (%s, %s, %s, %s) SELECT %s, %s, %s, %s FROM oldtable 
WHERE obj=%;" % ((name, desig, data, num), name, desig, data, num, repr(objkey))

But even then, you would need objkey defined somewhere as a python variable.

This answer may be way off, but you need to defined what you are expecting to achieve with obj = repr(objkey) , in order to get more accurate answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM