Answer a question

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?

Answers

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")
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐