无法加载python数据框到mysql

mklgxw1f  于 2023-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(129)

我试图加载一个python Dataframe 到mysql。它返回错误“处理格式参数失败; Python“timestamp”无法转换为MySQL类型“”。我不知道是关于什么的。

import pandas as pd
from datetime import date
import mysql.connector
from mysql.connector import Error
def priceStock(tickers):
  today = pd.to_datetime("today").strftime("%Y-%m-%d")
  for ticker in tickers:
    conn = mysql.connector.connect(host='103.200.22.212', database='analysis_stock', user='analysis_PhamThiLinhChi', password='Phamthilinhchi')
    
    new_record = stock_historical_data(ticker, '2018-01-01', today)
    new_record.insert(0, 'ticker', ticker)
    table = 'priceStock'
    cursor = conn.cursor()
        #loop through the data frame
    for i,row in new_record.iterrows():
    #here %s means string values 
        sql = "INSERT INTO " + table + " VALUES (%s,%s,%s,%s,%s,%s,%s)"

        #đoán chắc là do format time từ python sang sql ko khớp 
        cursor.execute(sql, tuple(row))
        print("Record inserted")
        # the connection is not auto committed by default, so we must commit to save our changes
        conn.commit()
priceStock(['VIC'])
elcex8rz

elcex8rz1#

而不是一次循环和插入一行,您可以使用to_sql一次性加载整个数据框to_sql使用SQLAlchemy并且SQLAlchemy支持MySQL,因此下面的代码应该可以工作

import pandas as pd
from datetime import date
import mysql.connector
from mysql.connector import Error
import sqlalchemy

def priceStock(tickers):
  today = pd.to_datetime("today").strftime("%Y-%m-%d")
  for ticker in tickers:
    conn = sqlalchemy.create_engine('mysql+mysqlconnector://analysis_PhamThiLinhChi:Phamthilinhchi@103.200.22.212')
    # conn = mysql.connector.connect(host='103.200.22.212', database='analysis_stock', user='analysis_PhamThiLinhChi', password='Phamthilinhchi')
    
    new_record = stock_historical_data(ticker, '2018-01-01', today)
    new_record.insert(0, 'ticker', ticker)
    table = 'priceStock'
    # cursor = conn.cursor()
    new_record.to_sql(table, con=conn, if_exists='append')
        #loop through the data frame
    # for i,row in new_record.iterrows():
    # #here %s means string values 
    #     sql = "INSERT INTO " + table + " VALUES (%s,%s,%s,%s,%s,%s,%s)"

    #     #đoán chắc là do format time từ python sang sql ko khớp 
    #     cursor.execute(sql, tuple(row))
    #     print("Record inserted")
    #     # the connection is not auto committed by default, so we must commit to save our changes
    #     conn.commit()
priceStock(['VIC'])

要查看更新的行,请使用以下代码:

from sqlalchemy import text
conn = sqlalchemy.create_engine('mysql+mysqlconnector://analysis_PhamThiLinhChi:Phamthilinhchi@103.200.22.212')
with conn.connect() as con:
   df = con.execute(text("SELECT * FROM priceStock")).fetchall()
   print(df)

相关问题