使用%s运算符在Python中创建MySQL数据库

时间:2019-06-23 17:08:44

标签: python mysql mysql-python

尝试创建一个数据库,该数据库的名称是通过%s运算符给出的。

import mysql.connector, MySQLdb
db_name='SomeString'

#create connection to mysql
mydb=mysql.connector.connect(host="localhost",user="root")

#init cursor
mycursor=mydb.cursor()

#create database
mycursor.execute("CREATE DATABASE (%s)", (db_name))

这是错误消息:

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(%s)' at line 1

1 个答案:

答案 0 :(得分:0)

我认为您打算插入db_name而不是%s的值,就像C中的占位符一样。如您所知,这不起作用。相反,您可以执行以下操作:

create_statement = "CREATE DATABASE {:s}".format(db_name)
mycursor.execute(create_statement)

以这种方式进行操作将使您可以在更复杂的情况下使用该技术,在这种情况下,要替换的值后面有更多的SQL。