Python和MySQLdb警告 [英] Python and MySQLdb warnings

查看:125
本文介绍了Python和MySQLdb警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个导出MSSQL数据并将其导入MySQL的程序.我有一个要导入的函数,如下所示:

I have a program that is exporting MSSQL data and importing it into MySQL. I have a function that is importing as follows:

def importMySql (mycursor,exportedfilename,table,delimiter):
    file_loc = str(sys.path[0] +"\\" +exportedfilename.lower()+".out").replace("\\", "\\\\")
    mycursor.execute("LOAD DATA LOCAL INFILE '%s' INTO TABLE %s FIELDS TERMINATED BY '%s' LINES TERMINATED BY '\r\n'" %(str(file_loc), table, delimiter))

光标(MySQLdb)发出以下警告:

the cursor (MySQLdb) is raising the following warnings:

C:\Users\tfy\Documents\PyProj\UTL (Export, Import, RDF)\eic.py:98: Warning: Data truncated for column 'DateofCharges' at row 1194
  mycursor.execute("LOAD DATA LOCAL INFILE '%s' INTO TABLE %s FIELDS TERMINATED BY '%s' LINES TERMINATED BY '\r\n'" %(str(file_loc), table, delimiter))
C:\Users\tfy\Documents\PyProj\UTL (Export, Import, RDF)\eic.py:98: Warning: Data truncated for column 'DateofCharges' at row 2009
  mycursor.execute("LOAD DATA LOCAL INFILE '%s' INTO TABLE %s FIELDS TERMINATED BY '%s' LINES TERMINATED BY '\r\n'" %(str(file_loc), table, delimiter))
C:\Users\tfy\Documents\PyProj\UTL (Export, Import, RDF)\eic.py:98: Warning: Data truncated for column 'DateofCharges' at row 4793
  mycursor.execute("LOAD DATA LOCAL INFILE '%s' INTO TABLE %s FIELDS TERMINATED BY '%s' LINES TERMINATED BY '\r\n'" %(str(file_loc), table, delimiter))

但是我需要将警告控制为仅输出:

but I need to control the warning to only output:

Warning: Data truncated for column 'DateofCharges' at row 1194
Warning: Data truncated for column 'DateofCharges' at row 2009
Warning: Data truncated for column 'DateofCharges' at row 4739

我环顾四周,发现了大量信息,这些信息说明了如何创建自定义警告.但是,不确定如何实现上述目标.我不想关闭警告,我只是想对它们进行格式化".我考虑过编辑实际的MySQLdb文件,但是它是.egg格式的,无法执行该操作.我也玩了warning.format(),但是没有成功.

I have looked around and found plenty of information that illustrates hows to create custom warnings. However, not sure how I would achieve the above. I do not want to turn off the warnings, I just want to "format" them. I thought about editing the actual MySQLdb file but it is in .egg format and unable to do that. I also played around warning.format() but was unsuccessful.

谢谢!

推荐答案

所以这是我找到的最简单的方法...不确定为什么我最初没有想到这一点...但是我只是抑制了由发出的警告光标:

So this is the easiest way I have found... Not sure why I did not think of this originally... but I simply suppressed the warnings issued by the cursor:

import warnings
warnings.filterwarnings("ignore", category = MySQLdb.Warning)

然后我将此代码添加到我的importMySql函数中:

I then added this code to my importMySql function:

mycursor.execute("SHOW WARNINGS")
warnings = mycursor.fetchall()
for i in range(len(warnings)):
    print "Warning - " +warnings[i][2]

这篇关于Python和MySQLdb警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆