【问题标题】:Create MySQL Database in Python using the %s operator使用 %s 运算符在 Python 中创建 MySQL 数据库
【发布时间】:2019-06-23 17:08:44
【问题描述】:

尝试创建一个通过 %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

【问题讨论】:

  • 欢迎来到 SO。您无需将%s 括在括号中。这就是导致语法错误的原因。 db_name 附近也不需要它们。
  • 谢谢!不幸的是,我已经尝试过不带括号的方法:mycursor.execute("CREATE DATABASE %s", db_name)。出现同样的错误:/
  • 对不起,有点暗!见答案。

标签: python mysql mysql-python


【解决方案1】:

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

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

这样做可以让您在更复杂的情况下使用该技术,在您尝试替换的值之后有更多 SQL。

【讨论】:

  • 你为什么写:s?我猜只有 {} 就足够了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-10
  • 2016-02-19
  • 2010-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多