我正在我的DB类中创建一个公共函数,它以dataframe作为参数并将数据插入到一个表中。我希望在其他模块中重用这个函数,因为大多数其他模块都会插入到这个表中。我正在考虑检查dataframe是否没有要插入的列,然后在列中插入null。应该向dataframe中添加加法列,但这意味着编辑原始的dataframe,并添加带有空值的其他列,或者其他方式是跳过插入中的列名,后者将在表中插入null (列为空)。记住可重用性和应用重要的面向对象的概念,实现这一目标的最佳方法是什么?
发布于 2019-04-29 02:30:54
如果您的表不太大,您可以很容易地做到这一点,遵循以下流程:
如果您的表不太大,您可以很容易地做到这一点,遵循以下流程:
ta = pd.read_sql('table', engine) #dataframe that exists already in SQL
tb #new dataframe that has columns that the other dataframe does not have
for i in list(tb.columns):
if i in list(ta.columns):
pass
else:
ta[i] = 'NULL'
tconso = ta.append(tb)
tconso.to_sql('table', engine, if_exists='replace')更新
因为您声明您的数据很大,所以您可以在sql中直接修改表,在外部执行附加内容:
1)导入库
import sqlalchemy
from sqlalchemy import create_engine, MetaData, Table, func, event
from sqlalchemy.sql import text
from urllib.parse import quote_plus2)联系:
params = urllib.parse.quote_plus(r'...')
conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params)
engine = create_engine(conn_str, echo=True)3)如果列是新列,则运行查询,并在添加新列后推送表:
ta = pd.read_sql('table', engine) #dataframe that exists already in SQL
tb #new dataframe that has columns that the other dataframe does not have
for i in list(tb.columns):
if i in list(ta.columns):
pass
else:
query = text('ALTER TABLE [dbo].[table] ADD ' + i + ' VARCHAR(50)')
connection = engine.connect()
connection.execute(query)
connection.close()
tb.to_sql('table', engine, if_exists=append),从新的DF中删除新列。
ta = pd.read_sql('table', engine) #dataframe that exists already in SQL
tb #new dataframe that has columns that the other dataframe does not have
for i in list(tb.columns):
if i in list(ta.columns):
pass
else:
tb.drop(columns=[i])
tb.to_sql('table', engine, if_exists=append)如果这有用的话请告诉我。BR
https://stackoverflow.com/questions/55896022
复制相似问题