mysql inser decimal_Python把MySQL查询转为Insert语句

#!/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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值