在MySQL命令中使用%s时出现问题

时间:2020-02-22 00:30:20

标签: python mysql

我正在尝试自动化(通过使用python脚本)创建MySQL角色的能力,但是由于某些原因,我无法将字符串变量放入mysql命令中。这是到目前为止我得到的:

#!/usr/bin/python3

import  mysql.connector
from    mysql.connector import errorcode 


# Open database connection
try:

        serverHostName='localhost'
        userName='root'
        passwd='password'
        databaseName='mysql'
        roleName='reader'

        cnx = mysql.connector.connect(
        host=serverHostName,
        database=databaseName, 
        user=userName, 
        password=passwd)

        cursor=cnx.cursor(prepared=True)
        dropRole="""DROP ROLE IF EXISTS %s """

        print(dropRole, roleName)
        #cursor.execute(dropRole, roleName)
        #cnx.commit()



except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Something is wrong with your user name or password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exist")
  else:
    print(err)
else:
  cnx.close()
  print("You have successfully disconnected from your MySQL database")

结果如下:

DROP ROLE IF EXISTS %s  reader
You have successfully disconnected from your MySQL database

如果有人可以向我解释为什么%s和读者出现在我的打印行中,将不胜感激。

1 个答案:

答案 0 :(得分:0)

您没有调用格式运算符将roleName替换为字符串,因此它只是打印格式字符串。使用%运算符执行格式化。

print(dropRole % roleName)