I'm currently writing a function in python that takes in user input and creates a database in SQL Server based on that input using PYODBC. My code is as follows:
import pyodbc
def input_creation():
input_db = int(input('What would you like to do? \n 1.) Create a Database \n 2.) Update a Database. Please select a number and press Enter'))
if input_db == 2:
print('Sorry, this option is not available as of yet. Please try again')
else:
input_server = input('What server?')
input_db_name = input('What would you like to call this Database?')
connStr = (
'Driver={ODBC Driver 17 for SQL Server};'
'Server=' + input_server + ';'
'Database=master;'
'Trusted_Connection=yes;'
)
#print(connStr)
cnxn = pyodbc.connect(connStr,autocommit = True)
crsr = cnxn.cursor()
crsr.execute('''
USE master
IF NOT EXISTS (
SELECT name
FROM sys.databases
WHERE name = N'{}')
CREATE DATABASE {} '''.format(input_db_name,input_db_name))
crsr.close()
When called, the function executes successfully with no errors. However, when looking through SQL Server Management Studio, it appears as if the database doesn't exist. The other questions pertaining to this issue seem to deal with the autocommit parameter not being specified in the .connect command, but that's not the case here. Any tips? Thank you in advance!