![](/img/trans.png)
[英]How to insert a Pandas Dataframe into MySql using PyMySQL
[英]Is there a way to insert dataframe into mysql using pymysql?
我有這個:
import pymysql
import pymysql.cursors
host = "localhost"
port=3306
user = "db"
password='pass'
db='test'
charset='utf8mb4'
cursorclass=pymysql.cursors.DictCursor
try:
connection= pymysql.connect(host=host,port=port,user=user,password=passw,db=db,charset=charset,cursorclass=cursorclass)
Executor=connection.cursor()
except Exception as e:
print(e)
sys.exit()
我嘗試使用pandas to_sql()
,但是它將表中的值替換為最新的。 我想使用Pandas將值插入表中,但是我想避免重復的條目,如果有的話,它應該被傳遞。
可以對數據框進行腌制並將其插入到BLOB
類型的列下的表中。 如果您采用這種方式,則必須將mysqld返回的結果發送出去
編輯:我看到你現在想做什么。 這是一個可能的解決方案。 讓我知道它是否有效!
# assume you have declared df and connection
records = df.to_dict(orient = 'records')
for record in records:
sql = "INSERT INTO mytable ({0}) \
VALUES ({1})".format(record.keys(), record.values())
curs = connection.cursor()
try:
curs.execute(sql)
curs.close()
except:
break #handle/research the error
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.