简体   繁体   English

MySQL/Python 无法将字典插入数据库

[英]MySQL/Python can't insert dict into database

I am currently having troubles inserting into MYSQL DB using python.我目前在使用 python 插入 MYSQL DB 时遇到问题。 The execute statement below dosen't run, which I found out using print stmts.下面的执行语句没有运行,这是我使用 print stmts 发现的。

This is a mystery to me as while using the same codes, my friends are able to insert into their DB (Of course using the appropriate mysql host, password etc. and the same mysql and python version)这对我来说是个谜,因为在使用相同的代码时,我的朋友可以插入他们的数据库(当然使用适当的 mysql 主机、密码等以及相同的 mysql 和 python 版本)

mycursor.execute("""
            INSERT INTO emailcontent (Subject, Date, Sender, Sendee, Message_body)
            VALUES (%(Subject)s, %(Date)s, %(Sender)s, %(To)s, %(Message_body)s)
            """, temp_dict)
            mydb.commit()

temp_dict example data: temp_dict 示例数据:

{'Subject': 'Security alert', 'Date': '2020-12-28', 'Sender': 'Google <no-reply@accounts.google.com>', 'Snippet': 'Quickstart was granted access to your Google Account sometestemail@gmail.com If you did not grant access, you should check this activity and secure your account. Check activity You can also see security', 
'To': 'sometestemail@gmail.com'}

Other codes:其他代码:

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="root",
  database="database"
)

mycursor = mydb.cursor()

Versions版本

Python 3.9.1 Python 3.9.1

mysql 8.0.22 mysql 8.0.22

mysql-connector 2.2.9 mysql 连接器 2.2.9

There's no Message_body item in your dictionary.您的字典中没有Message_body项。 You do have Snippet .你确实有Snippet Try that.试试看。

Referring to an answer posted here Using a Python dict for a SQL INSERT statement by furicle参考此处发布的答案Using a Python dict for a SQL INSERT statement by furicle

Managed to insert using the following:使用以下方法管理插入:

table = 'emailcontent'
            
placeholders = ', '.join(['%s'] * len(temp_dict))
columns = ', '.join(temp_dict.keys())
sql = "INSERT INTO emailcontent (Subject, Date, Sender, Sendee, Message_body) VALUES ( %s )" % (placeholders)

mycursor.execute(sql, list(temp_dict.values()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM