“CREATE … statement not allowed within multi-statement transaction” when using pyodbc

最后都变了- 提交于 2019-11-27 06:58:06

问题


I'm trying to create a SQL Server database using pyodbc.

import pyodbc 
server = 'AMR112\NAMED1' 
database = 'msdb' 
username = '' 
password = 'mypassword' 
abcd='yes' 
ghi='False' 
#driver = '{/usr/local/lib/libtdsodbc.so}' #for linux of windows 
driver= '{ODBC Driver 13 for SQL Server}' 
cnxn = pyodbc.connect('DRIVER='+driver+';PORT=1433;SERVER='+server+??';PORT=1443;DATABASE??='+database+';UID='+??username+';PWD='+ password+';trusted_connection='+ abcd+'; autocommit='+ ghi) cursor = cnxn.cursor() 
cursor.execute("create database dbafgh") 
row = cursor.fetchone() 
if row: 
    print row 
cursor.close()

It fails with this error

CREATE DATABASE statement not allowed within multi-statement transaction

It fails because the .execute method starts a transaction and CREATE DATABASE cannot be run within a transaction.

So is there any other way to execute a CREATE DATABASE command using python?


回答1:


When establishing a connection, pyodbc defaults to autocommit=False in accordance with Python's DB-API spec. Therefore when the first SQL statement is executed, ODBC begins a database transaction that remains in effect until the Python code does a .commit() or a .rollback() on the connection.

SQL Server does not allow CREATE DATABASE to be executed within such a transaction, so we need to have the connection in autocommit mode before issuing such statements. That can be accomplished when the connection is opened ...

conn = pyodbc.connect(conn_str, autocommit=True)

... or by switching to autocommit mode if the connection is already established:

conn = pyodbc.connect(conn_str)  # autocommit=False by default
# ...
conn.autocommit = True
conn.execute("CREATE DATABASE MyNewDatabase")


来源:https://stackoverflow.com/questions/42006192/create-statement-not-allowed-within-multi-statement-transaction-when-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!