简体   繁体   中英

Pandas Dataframe to_sql with a Decimal type

My Dataframe won't send to a SQLite database using the "to_sql" method, when the datatype is Decimal:

con = sqlite3.connect("test.db")
df = pd.DataFrame({"a":[decimal.Decimal(0)]})
df.to_sql(name="table", con=con)

error:

sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.

Is there a way around it? I would prefer to store the Decimal (in the database) as "text"

Hi I had the same problem, I solved it by converting the Decimal column in the Dataframe into a SQLAlchemy Numeric datatype:

import pandas as pd
from sqlalchemy import Numeric
from sqlalchemy import create_engine

engine = create_engine("sqlite:////test.db")
df = pd.DataFrame({"a":[decimal.Decimal(0)]}
df.to_sql(
        name="tariff",
        con=engine,
        dtype={"a": Numeric()}
    )
from sqlalchemy.types import DECIMAL
df.to_sql(name="table", con=con, dtype = {"a" : DECIMAL})

You can convert to decimal when sending the df to sql.

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