trapping a MySql warning

前端 未结 7 928
逝去的感伤
逝去的感伤 2020-11-29 23:59

In my python script I would like to trap a \"Data truncated for column \'xxx\'\" warning durnig my query using MySql.

I saw some posts suggesting the code below, but

相关标签:
7条回答
  • 2020-11-30 00:22

    Warnings are just that: warnings. They get reported to (usually) stderr, but nothing else is done. You can't catch them like exceptions because they aren't being raised.

    You can, however, configure what to do with warnings, and turn them off or turn them into exceptions, using the warnings module. For instance, warnings.filterwarnings('error', category=MySQLdb.Warning) to turn MySQLdb.Warning warnings into exceptions (in which case they would be caught using your try/except) or 'ignore' to not show them at all. You can (and probably should) have more fine-grained filters than just the category.

    0 讨论(0)
  • 2020-11-30 00:24

    Have you tried using MySQL's SHOW WARNINGS command?

    0 讨论(0)
  • 2020-11-30 00:29

    I would try first to set the sql_mode. You can do this at the session level. If you execute a:

    SET @@sql_mode:=TRADITIONAL;
    

    (you could also set it at the server level, but you need access to the server to do that. and, that setting an still be overridden at the session level, so the bottom line is, always set it at the session level, immediately after establishing the connection)

    then many things that are normally warnings become errors. I don't know how those manifest themselves at the python level, but the clear advantage is that the changes are not stored in the database. See: http://dev.mysql.com/doc/refman/5.1/en/server-sql-mode.html#sqlmode_traditional

    0 讨论(0)
  • 2020-11-30 00:35

    Raise MySQL Warnings as errors:

    import warnings, MySQLdb
    warnings.filterwarnings('error', category=MySQLdb.Warning)
    

    To ignore instead of raising an error, replace "error" with "ignore".

    Handle them in a try-except block like:

    try:
        # a MySQL DB operation that raises a warning
        # for example: a data truncated warning
    except Warning as a_warning:
        # do something here
    
    0 讨论(0)
  • 2020-11-30 00:35

    Stop using MySQLdb. It has such stupid behavior as truncating data and issuing only a warning. Use oursql instead.

    0 讨论(0)
  • 2020-11-30 00:36

    Just to add to Thomas Wouters reply, there is no need to import the warnings module to turn them into errors. Just run your script with "-W error" (or ignore) as flag for Python.

    0 讨论(0)
提交回复
热议问题