mysqlconnector创建语句上的Python错误1064

时间:2019-07-09 02:01:17

标签: python mysql mysql-python mysql-connector

我正在尝试创建一个小型数据库,用户可以在其中创建一个新数据库来存储信息。

我正在尝试让用户输入并运行不存在的CREATE DATABASE,但是我似乎遇到了出现1064(42000)错误的问题。

具体地说,它显示为:

  

mysql.connector.errors.ProgrammingError:1064(42000):您的SQL语法有一个错误。检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以在第1行使用新的“ test_client”。

我有一个单独的类,称为build,该类专门用于根据用户的请求创建数据库或表。

这里的问题是我有一种有效的代码方法,而另一种无效。我试图了解导致此问题的原因,因为我试图确保该代码免受任何sql注入的影响。

我尝试用两种方式编写代码:

  1. 用户输入存储在名为“ name”的变量中。 我有一段代码,如果名称中有空格,则添加一个“ _”。 我有一个变量(称为sqlFormula),其中包含代码: 然后将它们都运行到mycursor.execute中。 这就是我得到错误的地方。

代码:

    name = re.sub("\s+", "_", name)
    sqlFormula = ("""CREATE DATABASE IF NOT EXISTS %s""")
    mycursor.execute(sqlFormula, (name,))

这是产生错误的版本。

  1. 第二种有效的方法是执行以下操作:

    name =  = re.sub("\s+", "_", name)
    sqlFormula = """CREATE DATABASE IF NOT EXISTS %s"""%name
    mycursor.execute(sqlFormula)

这不会产生错误。

此部分涉及的部分代码如下:

class Build():
    __slots__ = ['userentry', 'database']

    def __init__ (self, used_database, user_entry = None)
        self.database = used_database
        self.userentry = user_entry

    def create_database (self)
        mycursor = self.database.cursor()
        name = re.sub("\s+", "_", name)
        sqlFormula = ("""CREATE DATABASE IF NOT EXISTS %s""")
        mycursor.execute(sqlFormula, (name,))
        mycursor.close()

class Create()
    def Create_table():
        user_input = input("What is the name of the database to create?")
        #a separate variable called db is used to house the db connection.
        Build(db, user_input).create_database()


I expected that by using the variable name in a tuple and the %s placeholder, that it would work without any problem. However I just keep getting the error.

0 个答案:

没有答案