python - 使用 python 通过 SQLAlchemy 引擎将 panda 数据框更新到 SQL Server

标签 python sql-server dataframe sqlalchemy

我有一个现有的 SQL Server 数据库。我想使用 python 读取 CSV 文件并将与 TIMEID 列匹配的列值更新到 SQL Server 表中

如果我在 SQL Server 中执行此操作,我会将新的 CSV 加载到新表中,然后使用以下方法进行更新:

UPDATE R 
SET R.[PA]=P.[PA]
FROM [DATABASE_TABLE] AS R
INNER JOIN [NEW_CSV] AS P 
       ON R.[TIMEID] = P.[TIMEID] 
WHERE R.[TIMEID] like '20180201%' //i can survive now without the where, and update everything from the CSV. 

对 python 很陌生,请原谅我。我已成功将 CSV 文件加载到 panda 数据框中,并且我还能够将新行插入 SQL Server,但无法管理更新(无论是现有列还是空列)。

import pandas as pd 
from sqlalchemy import create_engine
engine = create_engine("BLOCKOUTFOR PASSWORD")
query="SELECT * FROM [DATABASE].[TABLE]"
df = pd.read_sql_query(query, engine)
display(df) #This is just to display the current data

    TIMEID  DATEID  HOUR    DOW FESTIVAL    PA  PB  PC  P31A    PX  PY  P_TOT
0   20180101H01 2018-01-01  01  2   N   0.4615  0.0570  0.4427  0.0153  None    None    0.9765
1   20180101H02 2018-01-01  02  2   N   0.4112  0.0516  0.4074  0.0154  None    None    0.8856

#Convert Type and Load CSV into df3
def dfReadCSV( Path, Ind):
    df =pd.read_csv(Path,dtype={'DATEID':str,'Hour':str},parse_dates= ['DATEID'])
    df1=df[Ind:]
    return df1
df3=dfReadCSV("C5Liq_2018Test.csv",0)

display(df3) #if there is a neater way to do this it be appreciated, but not critical 

    Attribute   TIMEID  DATEID  Hour    DOW 20A 20DHA   21A 21DHA   30A 31A PA  PB  PC  P31A    P_TOT
0   H01 20180101H01 2018-01-01  01  1   0.2953  0.0158  0.1662  0.0412  0.4427  0.0153  0.4615  0.0570  0.4427  0.0153  0.9765
1   H02 20180101H02 2018-01-01  02  1   0.2711  0.0160  0.1401  0.0356  0.4074  0.0154  0.4112  0.0516  0.4074  0.0154  0.8856

#Insert Function
connStr= engine.connect().connection
cursor = connStr.cursor()

for index,row in df3.iterrows():
    cursor.execute('INSERT INTO [DATABASE].[TABLE]([TIMEID],[DATEID],[Hour],[DOW]) values (?,?,?,?)', row['TIMEID'], row['DATEID'], row['Hour'], row['DOW']) 
    connStr.commit()

cursor.close()
connStr.close()

#Update Function. This is where i have problem.
connStr= engine.connect().connection
cursor = connStr.cursor()

for row in df3.iterrows():
    #sql = 'UPDATE [DATABASE].[TABLE] SET [DATEID]=? WHERE [TIMEID]=?'.format(tbl=[DATABASE].[TABLE])
   cursor.execute("UPDATE [DATABASE].[TABLE]  SET [DATEID] = ? WHERE [TIMEID] = ?", row[:,0],row[;,0])  

cursor.close()
connStr.close()

语法错误,我无法弄清楚。我更喜欢使用与上面类似的方法进行更新。CSV 中的数据得到更新,我想将这些信息更新到我的 SQL Server 表中。

我找到了一个类似的帖子,但也没有找到答案: Update MSSQL table through SQLAlchemy using dataframes

作为那里的线程启动者,我也无法删除该表,因为我在新数据列(例如 PX)中加载的新 CSV 可能没有先前插入 (PA) 的一些信息。

最佳答案

有两种方法可以进行所需的更新:

1)直接在数据库上:

upd = (session.query(TABLE)
       .filter(TIMEID = row[:,0])
       .update({"DATEID": row[:,0]})
       )
print("# of updated rows = {}".format(upd))
# session.commit()

2) 加载对象、更新值并提交 session

upd = (session.query(TABLE)
       .filter(TIMEID = row[:,0])
       )

# assuming there should be exactly one object for given TIMEID
DATEID= upd.one()
DATEID.time_out = datetime.datetime.now()
session.commit()

您可以获得更多info

我不推荐使用sqlachemy进行更新。它适合批量插入

对于sqlalchemy

import pandas as pd
from sqlalchemy import create_engine
engine = create_engine('postgresql+psycopg2://postgres:password@host:port/database')
print(engine)
truncate_query = "SELECT * from something.something"
df = pd.read_sql_query(truncate_query , engine)

关于python - 使用 python 通过 SQLAlchemy 引擎将 panda 数据框更新到 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57357133/

相关文章:

c# - EF6 从数据库返回错误数据

python - 用 python 编写的博客引擎列表

sql-server - nvarchar和varchar的空间分配

sql - 我想在存储过程中传递一个选择查询作为参数

python - 如何在 Python DataFrame 中的确定行之前添加空行?

python - 将逗号分隔值从 mysql 加载到 python 中的数据框

python - Keras 中的图像序列处理 ConvLSTM 与 LSTM 架构

python - 如何配置环境以使用 LLVM Clang 构建 python 嵌入式 c 代码

python - 使用 Pandas Dataframe 制作调色板

从多个列名称中删除第一个字符