使用QUOTENAME

时间:2019-03-17 06:30:40

标签: python-3.x python-2.7 azure-sql-database pyodbc

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)  

正在获取错误消息,例如pyodbc.ProgrammingError :(“ 42S22”,u“ [42S22] [Microsoft] [用于SQL Server的ODBC驱动程序17] [SQL Server]无效的列名“ abcd”。(207)(SQLExecDirectW)” )”

1 个答案:

答案 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)