簡體   English   中英

Python-如何根據DF和其中的數據制作SQL“創建表”語句?

[英]Python - how to make SQL "Create Table" statement based on DF and data in it?

我將數據(來自 CSV 或 Excel)加載到 Python 的 Panda DF 中。

import pandas as pd
df = pd.read_csv('table1.csv')

數據如下所示:

c1,c2,c3
1,abc,1.5
2,bcd,2.53
3,agf,3.571

如何根據數據框中的數據create table statement SQL create table statement ,在本例中為:

create table table1 (c1 int, c2 varchar(3), c3 float);

謝謝。

您可以為正在處理的任何其他數據類型添加循環。 結果應該是一個包含列名和數據類型的 create table 語句。

#Get rid of invalid characters in the column names
Col_list = []
for i in range(df.shape[1]):   
    Col_Name = df.columns[i].replace(" - ", "_").replace(" ", "_").replace("&", "and") # Some characters were unacceptable
    Col_list.append(Col_Name)
df.columns = Col_list


#This function creates a create table statement out of my dataframe columns and data types
Text_list = []
for i in range(df.shape[1]):   
    Col_Name = df.columns[i]
    Python = df.convert_dtypes().dtypes[i]  # Most of the data types were listed as object so this reassigns them
    if Python == float:
        Oralce = "FLOAT"
    elif Python == 'datetime64[ns]':
        Oracle = 'DATE'
    elif Python == 'Int64':
        Oracle = "NUMBER"
    else:
        Oracle = "VARCHAR2(50)"
    Text_list.append(Col_Name)
    Text_list.append(' ')
    Text_list.append(Oracle)
    if i < (df.shape[1] - 1): 
        Text_list.append(", ")
Text_Block = ''.join(Text_list)
Text_Block

cursor = conn.cursor()

drop = """
drop TABLE tableName
"""
create = """
    CREATE TABLE tableName (
    {}    )
""".format(Text_Block)

cursor.execute(drop)
cursor.execute(create)
cursor.execute("commit")
cursor.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM