【问题标题】:Insert Python DuckDB table into SQL statement将 Python DuckDB 表插入 SQL 语句
【发布时间】:2021-09-14 04:16:53
【问题描述】:

我正在尝试使用已注册的虚拟表作为 SQL 语句中的表,并使用与另一个数据库的连接。我不能只是将列转换为字符串并使用它,我需要表/数据框本身在语句中工作并与 SQL 语句中的其他表连接。我正在一个 Access 数据库上尝试这个来启动。这是我目前所拥有的:

import pyodbc
import pandas as pd
import duckdb
conn = duckdb.connect()

starterset = pd.read_excel (r'e:\Data Analytics\Python_Projects\Applications\DB_Test.xlsx')

conn.register("test_starter", starterset)
IDS = conn.execute("SELECT * FROM test_starter WHERE ProjectID > 1").fetchdf()

StartDate = '1/1/2015'
EndDate = '12/1/2021'

# establish the connection
connt = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=E:\Databases\Offline.accdb;')
cursor = conn.cursor()

# Run the query
query = ("Select ProjectID, Revenue, ClosedDate from Projects INNER JOIN " + IDS + " Z on Z.ProjectID = Projects.ProjectID "
"where ClosedDate between #" + StartDate + "# and #" + EndDate + "# AND Revenue > 0 order by ClosedDate")
sfd
df = pd.read_sql(query, connt)
    
df.to_excel(r'TEMP.xlsx', index=False)
os.system("start EXCEL.EXE TEMP.xlsx")

# Close the connection
cursor.close()
connt.close()

我在 Excel 工作表中有一个 ID 列表,我试图将其用作数据库查询的过滤器。最终,这将在同一个表格中形成几个标准:日期、收入和 ID 等。
老实说,我很惊讶我在做这件事时遇到了这么多麻烦。在 SAS 中,使用 PROC SQL 非常简单,但是我无法获得一个数据框来按照我的需要在 SQL 参数中进行接口。我是否犯了语法错误?
迄今为止最常见的错误是“UFuncTypeError: ufunc 'add' 不包含带有签名匹配类型的循环 (dtype(' dtype('

【问题讨论】:

    标签: python sql pandas duckdb


    【解决方案1】:

    看起来您正在将 DataFrame 的内容推送到 Access 数据库查询中。我不认为 Pandas 有本地方法可以做到这一点。我使用的技术是特定于数据库供应商的,但我只是将文本字符串构建为 CTE/WITH 子句或临时表。 前任: """与 my_data 作为 ( 选择 'raw_text_within_df' 作为 df_column1,'raw_text_within_df' 作为 df_column2
    联合所有 选择 'raw_text_within_df' 作为 df_column1,'raw_text_within_df' 作为 df_column2
    联合所有 ... ) [您在此处的原始查询] """

    【讨论】:

      猜你喜欢
      • 2012-03-19
      • 2015-04-03
      • 1970-01-01
      • 2023-03-17
      • 2018-12-28
      • 1970-01-01
      • 1970-01-01
      • 2012-01-30
      • 1970-01-01
      相关资源
      最近更新 更多