使用 Python MySQL 连接器传递变量

Passing variables with Python MySQL connector

所以我有一个 Python 脚本,用于将 Discord 与我的网站同步的所有意图和目的。我正在将消息保存到数据库或尝试这样做。我一直收到一条错误消息,说我的语法有错误。我已经多次阅读有关此事的所有文档,但仍未找到原因或解决方案。下面是我现在正在使用的脚本的一部分。任何想法表示赞赏! print yes 和 print no 仅用于诊断,直到我开始工作为止。最终,每个 space.

中会有更多的脚本
@client.event
async def on_message(message):
    channel = message.channel
    guild = message.guild
    mycursor = mydb.cursor()
    mycursor.execute("SHOW DATABASES")
    author=message.author
    headers=(guild,author)
    if guild in mycursor:
        print("yes")
    else:
        print("no")
        mycursor.execute("CREATE DATABASE %s",guild)
        mycursor.execute("CREATE TABLE %s (message VARCHAR(255) %s (author VARCHAR(255)",headers)

这是我得到的错误。

root@viktor:~# python3 bot2.py
Bot Loaded
no  # <---- (This is the print no if there is not a database with the same name as the guild.)
Ignoring exception in on_message
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/discord/client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "bot2.py", line 95, in on_message
    mycursor.execute("CREATE DATABASE %s",guild)
  File "/usr/local/lib/python3.6/dist-packages/mysql/connector/cursor.py", line 551, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "/usr/local/lib/python3.6/dist-packages/mysql/connector/connection.py", line 490, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "/usr/local/lib/python3.6/dist-packages/mysql/connector/connection.py", line 395, in _handle_result
    raise errors.get_exception(packet)
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
mycursor.execute("CREATE TABLE %s (message VARCHAR(255)",channel)

您在此处 query/command 中缺少右括号。

以后,在询问具体错误时,您应该提供完整的回溯。

好的,所以仍然不确定问题出在哪里,但我确实找到了解决方案。

我只是更改了设置命令执行的方式。

cmd="CREATE DATABASE " + guild
mycursor.execute(cmd)