Unable to CREATE DATABASE via PyODBC connection

僤鯓⒐⒋嵵緔 提交于 2019-12-13 18:28:45

问题


I am using pyodbc in python 2.7 with MS SQL Server 2008R.

Here is my code for creating a database (the SQL code which works fine in SQL alone, but crash when executed in python)

SQL_command = """
                IF EXISTS(SELECT * FROM sys.databases WHERE [name] = 'NewDatabase')
                    DROP DATABASE NewDatabase
              """

conn.cursor.execute(SQL_command)

SQL_command = """
                CREATE DATABASE NewDatabase
                ON     
                (
                     NAME = 'NewDatabase_data'
                ,    FILENAME='D:\MSSQL\DATA\NewDatabase_data.mdf' 
                ,    SIZE = 4096KB 
                ,    FILEGROWTH = 4096KB 
                ) 
                LOG ON  
                (
                    NAME = 'NewDatabase_log'
                ,   FILENAME='D:\MSSQL\LOG\NewDatabase_log.ldf' 
                ,    SIZE = 4096KB 
                ,    FILEGROWTH = 10%
                ) 
                COLLATE SQL_Latin1_General_CP1_CI_AS
              """

conn.cursor.execute(SQL_command)

SQL_command = """
                ALTER DATABASE 
                    NewDatabase
                SET RECOVERY SIMPLE
              """

conn.cursor.execute(SQL_command)

However, I've got following error message:

pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]CREATE DATABASE statement not allowed within multi-statement transaction. (226) (SQLExecDirectW)')

May I know what is wrong with my code?

Many thanks.

====================================================================================

So, after taking the advice from @Matthias, I've executed commit after the drop database, then the error message became:

pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]CREATE FILE encountered operating system error 123(failed to retrieve text for this error. Reason: 15105) while attempting to open or create the physical file 'D:\MSSQL\DATA\NewDatabase_data.mdf'. (5123) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]CREATE DATABASE failed. Some file names listed could not be created. Check related errors. (1802)")

来源:https://stackoverflow.com/questions/27440711/unable-to-create-database-via-pyodbc-connection

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