简体   繁体   中英

How do I import python table data into an sql table?

import mysql.connector

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

import yfinance as yf
ticker = yf.Ticker("MSFT")
hist=ticker.history(period="max")

column_str = """id, Date, Open, High, 
          Low, Close, Volume, Dividends, Stock Splits"""
insert_str = ("%s, " * 9)[:-2]
final_str = "INSERT INTO historical_price (%s) VALUES (%s)" % (column_str, insert_str)

mycursor.execute(final_str, hist)
mydb.commit()

I get the error "The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."

How can I approach this?

You are trying to insert an entire dataframe into a table. The parameters keyword of execute can only accept a tuple or a dictonary . You probably need to iterate over the entire dataframe and enter the data per row. Something along the lines of (not tested):

for index, row in hist.iterrows():
    mycursor.execute(final_str, row)
mydb.commit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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