简体   繁体   English

使用python将mysql数据从一个表插入到另一个表

[英]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. 我正在尝试使用python将一个mysql表中已经存在的数据插入另一个表中。 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. 每个表中的列名都相同,并且objkey是我要用来告诉mysql要查看哪些列的项的唯一数据。

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). 我不确定您要使用obj = repr(objkey)行做什么,但是python认为您正在用此行定义变量,而不是设置sql语法(如果这确实是您的期望)。

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. 但是即使那样,您仍然需要objkey某个地方将objkey定义为python变量。

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. 这个答案可能obj = repr(objkey) ,但是为了获得更准确的答案,您需要定义obj = repr(objkey)期望实现的obj = repr(objkey)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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