简体   繁体   中英

Python try except to drop or create table in sql server

I am using pyodbc to create or drop table. 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. Anyone have idea how to revise this?

As @Brendan Abel suggested, your exception ProgrammingError is out of scope. Make an import like :

from pyodbc import ProgrammingError

or

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.

This exception you're getting is a NameError , because ProgrammingError isn't defined in the current scope. Exceptions are objects just like everything else in python, and you have to import or reference them from the correct places.

You probably want to do

try:
    cur.execute('Drop table {}'.format(table_name))
except pyodbc.ProgrammingError:
    cur.execute(create_table)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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