使用%s运算符在Python中创建MySQL数据库 [英] Create MySQL Database in Python using the %s operator
本文介绍了使用%s运算符在Python中创建MySQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试创建一个数据库,该数据库的名称是通过%s运算符给出的.
Trying to create a database where the name is given through the %s operator.
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
中的占位符一样.如您所知,这不起作用.相反,您可以执行以下操作:
I think you are intending the value of db_name
to be inserted instead of the %s
, like a placeholder in C
. This doesn't work as you have found out. Instead, you could do something like:
create_statement = "CREATE DATABASE {:s}".format(db_name)
mycursor.execute(create_statement)
以这种方式进行操作将使您可以在更复杂的情况下使用该技术,在这种情况下,要替换的值后面有更多的SQL.
Doing it this way will allow you to use the technique in more complex situations where there is more SQL after the value you are trying to substitute.
这篇关于使用%s运算符在Python中创建MySQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文