【问题标题】:Python - Insert in database tablePython - 在数据库表中插入
【发布时间】:2023-03-06 03:10:01
【问题描述】:

我有一个变量,我想将它的值插入到我的数据库表中。我有这个,但那不起作用:

import mysql.connector
import statistics
idk = []
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="",
  database="python"
)

mycursor = mydb.cursor()

mycursor.execute("SELECT `First Name` FROM employees")

myresult = mycursor.fetchall()

for x in myresult:
    idk.append(x)

y = statistics.mode(idk)
f = '( ,)'.join(y)

print(f)

mycursor.execute("INSERT INTO results (`First Name`) VALUES (%s)", f)

mydb.commit()

我得到这个错误:

mysql.connector.errors.ProgrammingError: 1064 (42000): 你的 SQL 语法有错误;查看与您的 MariaDB 服务器版本相对应的手册,了解在第 1 行的“%s)”附近使用的正确语法

【问题讨论】:

  • 通常执行函数需要您传递一系列参数,例如[f] 而不是 f。不过,这似乎不会导致 SQL 语法错误。
  • VALUES (%s) 应该是VALUES ('%s')
  • @Kaushal 不应该。
  • '( ,)'.join(y) 没有按照你的想法做。打印出来看看。
  • @JohnGordon 我也会这么说,但他们已经在打印了。

标签: python mysql python-3.x


【解决方案1】:

谢谢,我已经找到答案了。我只需要在 [] 中输入 f。

import mysql.connector
import statistics
idk = []
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="",
  database="python"
)

mycursor = mydb.cursor()

mycursor.execute("SELECT `First Name` FROM employees")

myresult = mycursor.fetchall()

for x in myresult:
    idk.append(x)

y = statistics.mode(idk)
f = '( ,)'.join(y)

print(f)

mycursor.execute("INSERT INTO results (`First Name`) VALUES (%s)", [f])

mydb.commit()

【讨论】:

    猜你喜欢
    • 2021-08-23
    • 2020-12-12
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多