- 论坛徽章:
- 0
|
本帖最后由 sancaiyujia 于 2017-07-27 09:46 编辑
import MySQLdb as mdb
import sys
def insert_db(param1,param2,param3):
db = mdb.connect(host='localhost',user='root',passwd='Password_123456',db='use_test',port=3306,charset='utf8')
cur = db.cursor()
insertsql="select * from %s.%s where id= %s" %(param1,param2,param3)
global result
try:
cur.execute(insertsql)
result = cur.fetchall()
if param2 == "test":
print 'insert into %s.%s values("%s","%s","%s","%s","%s");' %(param1,param2,result[0][0],result[0][1],result[0][2],result[0][3],result[0][4])
else :
print result
print 'insert into %s.%s values(%s,%s);' %(param1,param2,result[0][0],result[0][1])
except:
print("error: sql:" + insertsql+" result:"+str(result))
cur.close()
db.close()
return result
def update_db(param1,param2,param3):
db = mdb.connect(host='localhost',user='root',passwd='Password_123456',db='use_test',port=3306,charset='utf8')
cur = db.cursor()
updatesql="select * from %s.%s where id= %s" %(param1,param2,param3)
print updatesql
global result2
try:
cur.execute(updatesql)
result2 = cur.fetchall()
if param2 == "test":
print 'update %s.%s set id="%s",name="%s",age="%s",depno="%s",dept_name="%s";' %(param1,param2,result2[0][0],result2[0][1],result2[0][2],result2[0][3],result2[0][4])
else:
print 'update %s.%s set depno="%s",dept_name="%s";' %(param1,param2,result2[0][0],result2[0][1])
except:
print("error: sql:" + updatesql+" result:"+str(result2))
cur.close()
db.close()
return result2
if __name__ == "__main__":
conn =mdb.connect(host='localhost',user='root',passwd='Password_123456',db='use_test',port=3306,charset='utf8')
with conn:
cur = conn.cursor()
cur.execute("SELECT * FROM l_table_modify_d order by 1")
numrows = int(cur.rowcount)
for i in range(numrows):
row = cur.fetchone()
if row[3] == "insert":
insert_db(row[1],row[2],row[4])
# else:
# update_db(row[1],row[2],row[4])
cur.close()
conn.close()
----麻烦大家看看上面怎么修改可以用于一个脚本适应多张不同表,谢谢 |
|