下面贴出利用Python把MySQL查询结果转换为Insert语句,当然你使用一些客户端工具更方便了。但是有些需求没法使用工具搞了,比如我要把查询结果立马插入到另一个数据库中,并且查询结果中有些信息需要变更处理,这种使用脚本就很快了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
#!/usr/bin/env python # encoding: utf-8 # import MySQLdb import sys import datetime # 中文输出; reload(sys) sys.setdefaultencoding('utf8') # 连接数据库; try: connS = MySQLdb.connect( host='10.10.0.1', port=3306, user='root', passwd='123456', db='information_schema', charset='utf8', compress=1, connect_timeout=1 ) except BaseException: print "Could not connect to MySQL server." exit(1) # 查询结果为Json; cursorS = connS.cursor(cursorclass=MySQLdb.cursors.DictCursor) # 定义执行函数; def CreateTableInfo(TableName): sqlS = "select \ TABLE_SCHEMA, \ TABLE_NAME, \ TABLE_TYPE, \ ENGINE, \ ROW_FORMAT, \ TABLE_ROWS, \ DATA_LENGTH, \ INDEX_LENGTH, \ AUTO_INCREMENT, \ CREATE_TIME, \ UPDATE_TIME, \ TABLE_COLLATION, \ TABLE_COMMENT \ from information_schema.TABLES where TABLE_SCHEMA!='information_schema' and TABLE_SCHEMA!='mysql' and TABLE_SCHEMA!='performance_schema' and TABLE_SCHEMA!='test' and TABLE_SCHEMA!='sys';" # 判断查询语句是否正常; try: cursorS.execute(sqlS) rsS = cursorS.fetchall() except Exception as e: print(e) exit(1) # 判断查询结果是否有值; if not rsS: print('No Values') exit(1) # 处理查询结果; try: connS.begin() for RowDict in rsS: RowKey = ','.join(str(v) for v in RowDict.keys()) RowValue = ','.join( '\'' + str(v) + '\'' if isinstance( v, str) or isinstance( v, unicode) or isinstance( v, datetime.datetime) else str(v) for v in RowDict.values()) RowValue = RowValue.replace('None', 'NULL') InsertSQL = "insert into `%s`(%s) values (%s);" % (TableName , RowKey, RowValue) print(InsertSQL) connS.commit() except Exception as e: print(e) connS.rollback() if __name__ == '__main__': CreateTableInfo('tablename') cursorS.close() connS.close() |
脚本执行结果示例如下:
1 2 3 |
insert into `tablename`(ENGINE,ROW_FORMAT,UPDATE_TIME,TABLE_ROWS,INDEX_LENGTH,TABLE_TYPE,TABLE_SCHEMA,DATA_LENGTH,TABLE_COLLATION, CREATE_TIME,TABLE_NAME,AUTO_INCREMENT,TABLE_COMMENT) values ('InnoDB','Compact',NULL,214,0,'BASE TABLE','jdtable',65536,'utf8_unicode_ci','2017-09-20 16:50:16','UserClaimType',321,'信息'); |
可以看到字符型是字符型,NULL还是NULL,数值型还是数值型。这主要依赖于下面这个join。
1 2 3 4 5 6 7 8 9 10 |
RowValue = ','.join( '\'' + str(v) + '\'' if isinstance( v, str) or isinstance( v, unicode) or isinstance( v, datetime.datetime) else str(v) for v in RowDict.values()) |
把查询结果转换为字符串,并且会判断其类型。如果是字符串、unicode(Python 2输出还是unicode标识,Python 3统一为字符型)、时间都会加上分号,如果是数值型就原型显示(这些数据的类型在查询结果输出时就会有标识)。 如果觉得在join里面不好理解,也可以转换为下面这个格式:
1 2 3 4 5 6 7 8 9 10 |
val = '' for v in RowValue: if isinstance(v, str) \ or isinstance(v, unicode) \ or isinstance(v, datetime.datetime): val += '\'{}\''.format(v) else: val += str(v) val += ',' val = val.strip(',') |
脚本很简单,有同样需求的可以加以改造即可。