Create MySQL Database in Python using the %s operator

匆匆过客 提交于 2020-01-05 04:00:09

问题


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))

This is the error msg:

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:


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)

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.



来源:https://stackoverflow.com/questions/56726140/create-mysql-database-in-python-using-the-s-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!