1
votes
import pyodbc

con=pyodbc.connect('Driver={SQL Server};Server=New;Database=Countrydatabase;Trusted_connection=yes')
cur=con.cursor()
cur.execute("TRUNCATE Countrydatabase..region")   
con.close()

I am trying to truncate a table using the pyodbc module. But it keeps throwing an error.

Traceback (most recent call last): File "C:/Users/sean/Desktop/script.py", line 6, in cur.execute("TRUNCATE Countrydatabase..region") pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'Countrydatabase'. (102) (SQLExecDirectW)")

Same code works fine when I use "SELECT" statement.

4

4 Answers

5
votes

My issue with Truncate not working appears to be the Auto Commit setting wasn't working after I explicitly called con.close():

con = pyodbc.connect("conn", autocommit=True)

Or you can explicitly perform commits before closing:

con.commit()

Ref: https://stackoverflow.com/a/31611279/845584

4
votes

As the error messages shows, your SQL is incorrect.

It should be:

TRUNCATE TABLE region

(You don't need to specify the database, since you are connected to Countrydatabase already.)

1
votes

PeterX's comment above was my solution. I set autocommit=True when instantiating the command and my tables started to be truncated.

-1
votes

Have you tried to prefix it with dbo. something like: dbo.tablename

I was playing around with it today and had the same issue and adding the dbo part worked :-)