尝试在 pyodbc 中执行 SQL Server 命令但出现错误

时间:2021-03-26 04:03:41

标签: python sql sql-server tsql pyodbc

我一直在尝试使用pyodbc执行一些认为python脚本的SQL命令,但出现以下错误。

参考脚本代码

conn_info = f"DRIVER={driver};SERVER={server2};DATABASE=master;Trusted_Connection=yes;UID={uname2};PWD={passwd2}"
        cnct_str = pyodbc.connect(conn_info, autocommit=True)
        query = """CREATE USER {%s} WITH PASSWORD = '{%s}';"""% ((user_create,user_pass))
        print("<-----random generated passowrd is----->")
        print(user_pass)
        cur = cnct_str.cursor().execute(query)
        cur.commit()
        while cur.nextset():
            pass
    def post_restore2():
        conn_info = f"DRIVER={driver};SERVER={server2};DATABASE=master;Trusted_Connection=yes;UID={uname2};PWD={passwd2}"
        cnct_str = pyodbc.connect(conn_info, autocommit=True)
        query2 = """USE [{%s}] 
        CREATE USER {%s} WITH PASSWORD = '{%s}';
        GO
        EXEC sp_addrolemember N'db_owner', N'{%s}'
        GO"""% ((dba_name,user_create,user_pass,user_create))
        cur = cnct_str.cursor().execute(query2)
        while cur.nextset():
            pass

错误输出:

  Traceback (most recent call last):
  File "C:\Users\piyus\OneDrive\Desktop\sql_server_backup_restore_script.py", 
  line 129, in <module>
  post_restore1()
  File "C:\Users\piyus\OneDrive\Desktop\sql_server_backup_restore_script.py", 
  line 112, in post_restore1
  cur = cnct_str.cursor().execute(query)
   pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][SQL Server Native 
  Client 11.0]Syntax error, permission violation, or other nonspecific error 
  (0) (SQLExecDirectW)')

0 个答案:

没有答案