【问题标题】:Python and MySQLdb warningsPython 和 MySQLdb 警告
【发布时间】:2014-03-14 02:07:51
【问题描述】:

我有一个导出 MSSQL 数据并将其导入 MySQL 的程序。我有一个如下导入的函数:

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) 发出以下警告:

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))

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

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(),但没有成功。

谢谢!

【问题讨论】:

    标签: python mysql warnings mysql-python


    【解决方案1】:

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

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

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

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

    【讨论】:

      【解决方案2】:

      弄清楚这一点以使用 pprint。作为 OPs 解决方案,需要抑制默认警告,然后添加 show_warnings 函数,然后使用新的打印格式。

      from warnings import filterwarnings
      import MySQLdb as mdb
      from pprint import pprint
      
      filterwarnings('ignore', category = mdb.Warning)
      con = mdb.connect(...)
      cur = con.cursor()
      query = "Update table ..."
      cur.execute(query)
      con.commit()
      warnings = con.show_warnings() # return in tuple type
      pprint(warnings, width=100, depth=2) # width is the num of characters in each line, and depth is the level of the warnings in the tuple
      

      【讨论】:

        【解决方案3】:

        使用 MySQLdb

        您可以通过修补 MySQLdb 来实现此目的:

        import types
        
        def warning_check(self):
            if not self._warnings:
                self.messages = ()
                return
            self.messages = self._get_db().show_warnings()
        

        然后像这样在函数中修补 Cursor 对象:

        cur._warning_check = types.MethodType(warning_check, cur)
        

        然后,当你执行完LOAD DATA..,你就可以打印消息了:

        cur.execute("LOAD DATA..")
        for msg in cur.messages:
            print "Warning: {msg}".format(msg=msg[2])
        

        使用 MySQL 连接器/Python

        使用 MySQL 连接器/Python,您可以执行以下操作:

        cnx.get_warnings = True
        cur.execute("LOAD DATA..")
        for msg in cur.fetchwarnings():
            print "Warning: {msg}".format(msg=msg[2])
        

        (请注意,您需要使用连接参数 client_flags=[mysql.connector.ClientFlag.LOCAL_FILES] 设置客户端标志)

        【讨论】:

          【解决方案4】:

          可以在子进程中运行你的mysql代码吗?如果是这样,您可以使用 Python 的 subprocess 运行 mysql 代码,从 stdout 读取输出并相应地对其进行格式化。例如,使用process.stdout.readline()

          你可以参考这个问题:Starting and Controlling an External Process via STDIN/STDOUT with Python

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-01-20
            • 2011-11-10
            • 2011-11-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-12-12
            相关资源
            最近更新 更多