conn = pyodbc.connect("DRIVER={SQL Server};"
"SERVER="+server+";"
"UID="+username+";"
"PWD="+password,
autocommit=True)
cursor = conn.cursor()
database= "abcd"
sql_create = (
"DECLARE @sql AS NVARCHAR(MAX);"
"SET @sql = 'if not exists(select * from sys.databases where name = ' + QUOTENAME(?) + ')' + ' CREATE DATABASE ' + QUOTENAME(?);"
"EXEC sp_executesql @sql")
cursor.execute(sql_create,database,database)
答案 0 :(得分:0)
请勿对QUOTENAME
子句参数使用WHERE
和串联。另外,请避免使用Windows附带的旧式SQL Server
ODBC驱动程序来访问Azure SQL数据库。而是下载并使用newer ODBC driver。以下是这些更改的示例。
conn = pyodbc.connect("DRIVER={ODBC Driver 17 for SQL Server};"
"SERVER="+server+";"
"UID="+username+";"
"PWD="+password,
autocommit=True)
cursor = conn.cursor()
database= "abcd"
sql_create = (
"DECLARE @sql AS NVARCHAR(MAX);"
"SET @sql = N'if not exists(select * from sys.databases where name = @DatabaseName)' + N' CREATE DATABASE ' + QUOTENAME(?) + N';';"
"EXEC sp_executesql @sql, N'@DatabaseName sysname', @DatabaseName = ?;")
cursor.execute(sql_create,database,database)
您还可以为数据库名称声明一个T-SQL变量并将其分配给参数值,这样您只需要传递一个参数即可:
sql_create = (
"DECLARE @sql AS NVARCHAR(MAX);"
"DECLARE @DatabaseName sysname = ?;"
"SET @sql = N'if not exists(select * from sys.databases where name = @DatabaseName)' + N' CREATE DATABASE ' + QUOTENAME(@DatabaseName) + N';';"
"EXEC sp_executesql @sql, N'@DatabaseName sysname', @DatabaseName = @DatabaseName;")
cursor.execute(sql_create,database)