I have a problem that pandas to_sql function doesn't put correct dtypes to SQLite 3 database. It automatically detects types and ignores the types specified in the dictionary provided. I have tried a lot of variants or types writing like 'int', 'integer', 'float', 'real', 'floating', tried to show them directly or with use of sqlalchemy.types methods.
def generate_dtypes_for_sql(filename, separator, decimal, skip_errors, quoting, engine, shape):
df2 = pd.DataFrame()
if os.path.isfile(filename):
try:
df = load_csv(filename, separator, decimal, skip_errors, quoting, engine, shape)
params_to_import = {}
cols = df.columns
i_arc = 7; i_name = 6; i_type = 3; i_factor = 5
params_types = ['boolean', 'integer', 'float', 'text']
if (i_arc==cols.get_loc('Архивация') and
i_name==cols.get_loc('Символьный тэг') and
i_type==cols.get_loc('Тип')):
for index, row in df.iterrows():
if row[i_arc] == 1:
if math.isnan(row[i_type]):
params_to_import[row[i_name]] = params_types[3]
elif row[i_type] in range(6):
if row[i_factor] == 1:
params_to_import[row[i_name]] = params_types[1]
else:
params_to_import[row[i_name]] = params_types[2]
elif row[i_type] == 6:
params_to_import[row[i_name]] = params_types[2]
else:
params_to_import[row[i_name]] = params_types[3]
df2 = pd.DataFrame([params_to_import])
df2.T.to_csv("params_to_import.csv", sep=";", index_label="Name", header=['Type'])
except LoadCsvError as e:
click.echo("Could not load {}: {}".format(filename, e), err=True)
return df2
def sqlcol(dfparam):
dtypedict = {}
for index, values in dfparam.items():
for value in values:
if value == "boolean":
dtypedict.update({index: sqlalchemy.types.Boolean()})
elif value == "integer":
dtypedict.update({index: sqlalchemy.types.Integer()})
elif value == "float":
dtypedict.update({index: sqlalchemy.types.Float()})
elif value == "text":
dtypedict.update({index: sqlalchemy.types.Text()})
return dtypedict
df_for_sql = generate_dtypes_for_sql(types_file, separator, decimal, skip_errors, quoting, engine, shape)
df_dtypes = sqlcol(df_for_sql)
conn = sqlite3.connect(dbname, detect_types=sqlite3.PARSE_DECLTYPES)
df.to_sql(df.name, conn, if_exists="append", index=False, dtype=df_dtypes_str)
Solution: I don't know why but pandas to_sql function ignores dtype only if I use it with flag: if_exists="append". But if I use it with flag if_exists="replace", it works OK.
dtype=fix works for me.engineis a SQLAlchemyEngineobject created with thecreate_enginemethod.