我正在尝试创建一个小型数据库,用户可以在其中创建一个新数据库来存储信息。
我正在尝试让用户输入并运行不存在的CREATE DATABASE,但是我似乎遇到了出现1064(42000)错误的问题。
具体地说,它显示为:
mysql.connector.errors.ProgrammingError:1064(42000):您的SQL语法有一个错误。检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以在第1行使用新的“ test_client”。
我有一个单独的类,称为build,该类专门用于根据用户的请求创建数据库或表。
这里的问题是我有一种有效的代码方法,而另一种无效。我试图了解导致此问题的原因,因为我试图确保该代码免受任何sql注入的影响。
我尝试用两种方式编写代码:
代码:
name = re.sub("\s+", "_", name)
sqlFormula = ("""CREATE DATABASE IF NOT EXISTS %s""")
mycursor.execute(sqlFormula, (name,))
这是产生错误的版本。
第二种有效的方法是执行以下操作:
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.