#!/usr/bin/python# coding=utf-8importpymysql# 连接本地数据库conn=pymysql.connect(host='localhost',port=3306,user='root',passwd='yourpwd',db='samp_db1',charset='utf8')cursor=conn.cursor()cursor.execute('select * from bigstu')forrowincursor.fetchall():print(row)# 查cursor.execute('select id, name from bigstu where age > 22')forresincursor.fetchall():print(str(res[0])+", "+res[1])cursor.close()print('-- end --')
table="bigstu"addCash="update "+table+" set cash = cash + '%d' where name = '%s'"lucky=(1000,"秀吉")try:cursor.execute(addCash%lucky)exceptExceptionase:conn.rollback()print("加钱失败了")else:conn.commit()
importpymysqlimportjsonimportosimportsecureUtilsmapping_keys=json.load(open("key_mapping_db.json","r"))db_keys=[]# json中所有的keyforkinmapping_keys.values():db_keys.append(k)conn=pymysql.connect(host='localhost',port=3306,user='root',passwd='*****',db='db_name',charset='utf8')cursor=conn.cursor()table_main="table_main"main_table_keys=[]# 主表的列名cursor.execute("show columns from "+table_main)forrowincursor.fetchall():main_table_keys.append(row[0])staff_table_keys=[]cursor.execute("show columns from table_second")forrowincursor.fetchall():staff_table_keys.append(row[0])need_to_insert_keys=[]forkindb_keys:ifknotinstaff_table_keysandknotinmain_table_keysandknotinneed_to_insert_keys:need_to_insert_keys.append(k)print("need to insert "+str(len(need_to_insert_keys)))print(need_to_insert_keys)forkninneed_to_insert_keys:print("add key to db "+kn)cursor.execute("alter table staff_table add "+kn+" text")conn.close()
# change column character set to utf8forcoinmain_table_keys:change_sql="alter table "+table_main+" modify "+co+" text character set utf8"print(change_sql)cursor.execute(change_sql)