![](/img/trans.png)
[英]How to convert SQL Oracle Database into a Pandas DataFrame?
[英]Convert Pandas DataFrame WITHOUT connecting to a SQL database
我见过的所有解决方案都需要连接到 SQL 数据库,这不是这个问题的目标。
假设我有一个简单的 pandas DataFrame:
df = pd.DataFrame({{'hello'}:[1], {'world}:[2]})
...我想自动将其转换为可以执行以生成表的 .sql 文件,例如:
#psuedocode
py_script.output_file_sql('my_table')
return """CREATE TABLE my_table (
hello integer,
world integer
);""
在没有实际连接到数据库的情况下,我找不到将 pandas 转换为 an.sql 的文档。
如果我使用 sqlalchemy,则使用 information_schema.columns 或 \d table_name 运行查询似乎不起作用。
有什么建议么?
你需要 map 正确的所有数据类型,我只用了一个例子来告诉你如何开始。
但要正确,如果您想拥有所有选项,则需要重建所有https://www.postgresql.org/docs/current/sql-createtable.html
所以我重复我的评论,最好是使用备份工具在数据库服务器上备份数据库,然后改用 hat。
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))
结果是
CREATE TABLE Ones( hello bigint ,world bigint , PRIMARY KEY (hello))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.