All solutions I have seen require connecting to a SQL database, which IS NOT the goal of this question.
Let's say I have a simple pandas DataFrame:
df = pd.DataFrame({{'hello'}:[1], {'world}:[2]})
...and I wanted to automatically convert it into a.sql file that could be executed to generate the table, so something like:
#psuedocode
py_script.output_file_sql('my_table')
return """CREATE TABLE my_table (
hello integer,
world integer
);""
I can't find the documentation for pandas conversion into an.sql without actually connecting to a database.
If I use sqlalchemy, then run a query with information_schema.columns or \d table_name that doesn't seem to work.
Any suggestions?
you need to map all the datatypes correctly, i only used a sample to show you how top start.
But to be correct you need to rebuild all https://www.postgresql.org/docs/current/sql-createtable.html if you want to have all options
So i repeat my comment, best is to backup your database on database server with a backup tool, and use hat instead.
import pandas as pd
df = pd.DataFrame({'hello':[1], 'world':[2]})
df.name = 'Ones'
indextext = "hello"
def typeconversion(x):
return {
'int64': 'bigint ',
'float64': 'FLOAT'
}[x]
def get_sql(df,Indexx_table):
STR_sql = "CREATE TABLE " + df.name + "( "
for (col1, col2) in zip(df.columns, df.dtypes):
STR_sql += col1 + " " + typeconversion(col2.name) + ','
#remove last comma
STR_sql = STR_sql[:-1]
if Indexx_table:
STR_sql += ", PRIMARY KEY (" + Indexx_table + ")"
STR_sql += ")"
return STR_sql
print(get_sql(df,indextext))
result is
CREATE TABLE Ones( hello bigint ,world bigint , PRIMARY KEY (hello))
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.