[英]Python try except to drop or create table in sql server
I am using pyodbc to create or drop table. 我正在使用pyodbc创建或删除表。 And I wrote a function to drop table if table has already existed. 如果表已经存在,我写了一个删除表的函数。 Please look at my syntax below 请看下面我的语法
try:
cur.execute('Drop table {}'.format(table_name))
except ProgrammingError:
cur.execute(create_table)
However, I got error message : 但是,我收到错误消息:
<ipython-input-79-fe0fe29a1e8e> in upload_to_SQL(file_name, skiprows, table_name)
26 try:
27 cur.execute('Drop table {}'.format(table_name))
--->28 except ProgrammingError:
29 cur.execute(create_table)
30
NameError: name 'ProgrammingError' is not defined
I confirm that ProgrammingError is the error message if I drop a table didn't exist in the sql server. 如果删除sql服务器中不存在的表,我确认ProgrammingError是错误消息。 Anyone have idea how to revise this? 有人知道如何修改吗?
As @Brendan Abel suggested, your exception ProgrammingError
is out of scope. 正如@Brendan Abel所建议的,您的例外ProgrammingError
不在范围内。 Make an import
like : 像这样import
:
from pyodbc import ProgrammingError
or 要么
pyodbc.ProgrammingError
. pyodbc.ProgrammingError
。 Also would be nice to change your query a bit: 也可以稍微更改一下查询:
"DROP TABLE IF EXISTS {}".format(self.table_name)
Here is a list exceptions from pyodbc
docs. 这是pyodbc
文档中的例外列表。
This exception you're getting is a NameError
, because ProgrammingError
isn't defined in the current scope. 您遇到的此异常是NameError
,因为在当前范围中未定义ProgrammingError
。 Exceptions
are objects just like everything else in python, and you have to import or reference them from the correct places. Exceptions
是对象,就像python中的所有其他对象一样,您必须从正确的位置导入或引用它们。
You probably want to do 你可能想做
try:
cur.execute('Drop table {}'.format(table_name))
except pyodbc.ProgrammingError:
cur.execute(create_table)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.