简体   繁体   English

如何使用pymysql在python中连接mysql数据库,KEY ERROR

[英]how to connect mysql database in python using pymysql,KEY ERROR

im pretty new with python,im sorry if my question and my english doesnt sound right at all.我对 python 很陌生,如果我的问题和我的英语听起来不太对,我很抱歉。 ive been trying to integrated my scraping output to mysql,but unfortunately i got stuck.can you good people help me?我一直在尝试将我的抓取输出集成到 mysql,但不幸的是我被卡住了。你们好心人能帮帮我吗?

the output/error *<pymysql.cursors.Cursor object at 0x000000E81FF095E0> <pymysql.connections.Connection object at 0x000000E81FEF9070>输出/错误*<pymysql.cursors.Cursor object at 0x000000E81FF095E0> <pymysql.connections.Connection object at 0x000000E81FEF9070>

KeyError Traceback (most recent call last) in 9 data = csv.DictReader(scrapeddata) 10 for row in data: ---> 11 sql = "INSERT INTO emas ( tanggal, terakhir, pembukaan, tertinggi, terendah, vol, perubahan%) VALUES ('%s','%s','%s','%s','%s','%s','%s')" %(str(row["tanggal"]),str(row["terakhir"]),str(row["pembukaan"]),str(row["tertinggi"]),str(row["terendah"]),str(row["vol"]),str(row["perubahan%"])) 12 print(sql) 13 cur.execute(sql) KeyError Traceback(最近一次调用最后一次)在 9 个数据 = csv.DictReader(scrapeddata) 10 数据中的行:---> 11 sql = "INSERT INTO emas (tanggal, terakhir, pembukaan, tertinggi, terendah, vol, perubahan% ) 值 ('%s','%s','%s','%s','%s','%s','%s')" %(str(row["tanggal"]) ,str(row["terakhir"]),str(row["pembukaan"]),str(row["tertinggi"]),str(row["terendah"]),str(row["vol"]) ,str(row["perubahan%"])) 12 打印(sql) 13 cur.execute(sql)

KeyError: 'tanggal'* KeyError: 'tanggal'*

this is my code这是我的代码

import csv
import pymysql
#Connecting to MySQL in Windows
conn = pymysql.connect(host="127.0.0.1", port = 3306, user = "root", passwd = '', database = "mysql", 
charset = "utf8")
cur = conn.cursor()
cur.execute("USE historis")
print(cur)
print(conn)

with open(r'C:\Users\shulhan\output_emas.csv') as scrapeddata:
data = csv.DictReader(scrapeddata)
for row in data:
sql = "INSERT INTO emas ( tanggal, terakhir, pembukaan, tertinggi, terendah, vol, perubahan%) 
VALUES ('%s','%s','%s','%s','%s','%s','%s')"
    %(str(row["tanggal"]),str(row["terakhir"]),str(row["pembukaan"]),str(row["tertinggi"]),str(row["terendah"]),str(row["vol"]),str(row["perubahan%"]))
    print(sql)
    cur.execute(sql)
    conn.commit()

i think your connection setup should look like this:我认为您的连接设置应如下所示:

connection = pymysql.connect(host='localhost',
                         user='user',
                         password='passwd',
                         db='db',
                         charset='utf8mb4',
                         cursorclass=pymysql.cursors.DictCursor)

you can find more information here: https://pymysql.readthedocs.io/en/latest/user/examples.html您可以在此处找到更多信息: https : //pymysql.readthedocs.io/en/latest/user/examples.html

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

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