如何在 pandas 数据框和 SQL table 之间进行内部连接?

How to inner join between pandas dataframe and SQL table?

我正在尝试通过在我的服务器上本地计算的 pandas 数据帧和 SQL 之间的内部连接来更新 SQL table table 在带有 pyodbc 的远程服务器中,但我似乎无法匹配 dataframe/tables.

之间的键

我的第一个方法是创建一个简单的查询,在其中更新我需要的 3 列,使用数据框中的列和 SQL table 中的列之间的内部连接。但是,唉,它没有用,因为我受到了

的欢迎

pydobc 中使用的查询是:

   'UPDATE table1
   SET table1.col1 = ' + df[col1] + ', ' +
       'table1.col2 = ' + df[col2] + ', ' +
       'table1.col3 = ' + df[col3] +
   ' FROM table1 ' + 
   ' inner join ' + df[key_col] + ' on ' + df[key_col] + '= table1.key_col'

其中returns错误:

TypeError: The first argument to execute must be a string or unicode query.

我的第二种方法是使用循环并遍历数据帧的每一行,在数据帧和 SQL table:

之间连续匹配
SET table1.col1 = df[col1], 
    table1.col2 = df[col2], 
    table1.col3 = df[col3] 
FROM table1 
WHERE table1.key_col = df[key_col]

但是,由于数据框的大小,匹配它们之间的所有行最多需要一个小时。

我的预期结果是更新了table1中的三列,但实际上什么都没有更新。

我目前的解决方案是使用我需要的列和键在 SQL 中创建新的 table,然后使用另一个查询,在两者之间进行内部连接 ​​SQL tables 但这是一个临时解决方案。

这可以用 pyodbc 完成吗?我查看了文档,找不到任何有用的信息。

data = [tuple(x) for x in df.values]

cnxn = open_connection() # open the connection
crsr = cnxn.cursor()
crsr.fast_executemany = True # If you want it to run fast, but it will consume more memory
sql_string = """
        UPDATE table1
SET
    table1.col1 = ?,
    table1.col2 = ?,
    table1.col3 = ?
FROM
    table1
WHERE
    table1.key_col = ?
        """
crsr.executemany(sql_string, data)

请确保 ? 的顺序与数据元组的顺序相同。