简体   繁体   English

如何在 Python 中尝试除法和 sql 表语法错误?

[英]How to try-except and sql table syntax error in Python?

I have a code that puts some concatenated files into an SQL table (it's a loop).我有一个将一些连接文件放入 SQL 表的代码(它是一个循环)。 There's a configuration file where python reads the table name it should create and use in this code.有一个配置文件,python 在其中读取它应该在此代码中创建和使用的表名。 It works just fine.它工作得很好。

This is the code I execute:这是我执行的代码:


            startSQL = time.time()

            #write the concatenated files into the database. Chunksize may be changed
            xls.to_sql(table, con=engine, if_exists='append', index=False, chunksize=10000)

            #count inserted rows _ information for the log table
            countRow=engine.execute("select count(*) from "+table+ ";").fetchall()
            finalCount = (str(countRow).split('[(')[1].split(',)]')[0])
            

            endSQL = time.time()
            elapsed_timeSQL = round(endSQL-startSQL,2)

            logging.info("Table Creation+{}+{}+0+{}".format(table, elapsed_timeSQL,finalCount))
            
            #Just to confirm the table was created - can be deleted
            x=pd.read_sql("SELECT top 5 * FROM "+table , engine)
            print(x, 3 * "\n");

It does what it's needed.它做它需要的事情。

However, there are some syntaxes that you shouldn't use to create a table such as numbers, spaces, hyphens, etc. (as you can see in the following link )但是,您不应该使用某些语法来创建表格,例如数字、空格、连字符等(如以下链接所示)

What I need is to implement a try-catch or whatever to make sure that if an error occurs, it logs the error, but continues the rest of the code execution.我需要的是实现一个 try-catch 或其他任何东西,以确保如果发生错误,它会记录错误,但继续执行其余的代码。

NOTE:笔记:

Eg when I type the table name as 5table it gives me the following error and stops the script and that is exactly what I want to avoid!例如,当我将表名键入为5table时,它​​会给我以下错误并停止脚本,这正是我想要避免的! I want it to write a log saying that it failed and continue the code.我希望它写一个日志说它失败并继续代码。

Traceback (most recent call last):
  File "/home/XXX/.local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1820, in _execute_context
    cursor, statement, parameters, context
  File "/home/XXX/.local/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 732, in do_execute
    cursor.execute(statement, parameters)
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '5X'. (102) (SQLExecDirectW)")

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "XXX.py", line 353, in <module>

  File "XXX.py", line 339, in main
    fh.close()
  File "XXX.py", line 123, in process_file
    engine.execute("drop TABLE if exists "+table);
  File "<string>", line 2, in execute
  File "/home/XXX/.local/lib/python3.7/site-packages/sqlalchemy/util/deprecations.py", line 401, in warned
    return fn(*args, **kwargs)
  File "/home/XXX/.local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 3176, in execute
    return connection.execute(statement, *multiparams, **params)
  File "/home/XXX/.local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1296, in execute
    future=False,
  File "/home/XXX/.local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1602, in _exec_driver_sql
    distilled_parameters,
  File "/home/XXX/.local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1863, in _execute_context
    e, statement, parameters, cursor, context
  File "/home/XXX/.local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2044, in _handle_dbapi_exception
    sqlalchemy_exception, with_traceback=exc_info[2], from_=e
  File "/home/XXX/.local/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
    raise exception
  File "/home/XXX/.local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1820, in _execute_context
    cursor, statement, parameters, context
  File "/home/XXX/.local/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 732, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (pyodbc.ProgrammingError) ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '5E'. (102) (SQLExecDirectW)")
[SQL: drop TABLE if exists 5XXXX_example]

What I need is something like:我需要的是这样的:

try:
        #do the code above

except:
        #if there's the error regarding table syntax, write to the log and continue whatever it's doing
        print("Failed table {} creation!".format(table))
        logging.error("Failed creation of table+{}+0+0+0".format(table))


Please, help...请帮忙...

The Error can be caught like so:可以像这样捕获错误:

from sqlalchemy.exc import ProgrammingError

try:
    #do the code above
except ProgrammingError:
    #if there's the error regarding table syntax, write to the log and continue whatever it's doing
    print("Failed table {} creation!".format(table))
    logging.error("Failed creation of table+{}+0+0+0".format(table))

Edited my answer based on a comment from an other user根据其他用户的评论编辑了我的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM