How can I change password for sql login to database using pyodbc?

假如想象 提交于 2020-01-23 17:17:05

问题


I try change password for sql login to database using pyodbc in python

But I get error - Wrong syntax near object "@P1" (102) (SQLExecDirectW).....Cannot prepare the instruction (8180)

config.login = 'user'
config.haslo = '12345'
haslo = 'abcde'
con = pyodbc.connect("DRIVER={ODBC Driver 11 for SQL Server};"
                  "SERVER=Serwer;"
                  "DATABASE=Baza;"
                  "UID="+config.login+";"
                  "PWD="+config.haslo+";"
                  "autocommit=true")
kursor = con.cursor()
zapytanie = """ALTER LOGIN ? with password = ? old_password = ?"""
val = (config.login, haslo, config.haslo)
kursor.execute(zapytanie, val)
kursor.commit()
kursor.close()
del kursor

回答1:


SQL Server ODBC apparently does not support parameterization of an ALTER LOGIN statement. Instead of using this ...

uid = 'bubba'
old_pwd = 'NASCAR'
new_pwd = 'GRITS'
sql = "ALTER LOGIN ? WITH password ? old_password ?"
crsr.execute(sql, uid, new_pwd, old_pwd)

... you will need to do something like this:

uid = 'bubba'
old_pwd = 'NASCAR'
new_pwd = 'GRITS'
sql = f"ALTER LOGIN {uid} WITH PASSWORD = '{new_pwd}' OLD_PASSWORD = '{old_pwd}'"
crsr.execute(sql)

IMPORTANT - As with all dynamic SQL, this is potentially vulnerable to SQL injection issues. Be sure to sanitize the login_id and password values!

(Long-time users of SQL Server may recall that there is a system stored procedure named sp_password but the documentation indicates that it is deprecated.)



来源:https://stackoverflow.com/questions/56648034/how-can-i-change-password-for-sql-login-to-database-using-pyodbc

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