使用 %s 运算符在 Python 中创建 MySQL 数据库
Create MySQL Database in Python using the %s operator
正在尝试创建一个数据库,其中的名称是通过 %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
我认为您打算插入 db_name
的值而不是 %s
,就像 C
中的占位符一样。正如您所发现的那样,这不起作用。相反,您可以这样做:
create_statement = "CREATE DATABASE {:s}".format(db_name)
mycursor.execute(create_statement)
这样做将使您能够在更复杂的情况下使用该技术,在这些情况下,在您尝试替换的值之后有更多 SQL。
正在尝试创建一个数据库,其中的名称是通过 %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
我认为您打算插入 db_name
的值而不是 %s
,就像 C
中的占位符一样。正如您所发现的那样,这不起作用。相反,您可以这样做:
create_statement = "CREATE DATABASE {:s}".format(db_name)
mycursor.execute(create_statement)
这样做将使您能够在更复杂的情况下使用该技术,在这些情况下,在您尝试替换的值之后有更多 SQL。