【问题标题】:Python select from SQL table by datePython 按日期从 SQL 表中选择
【发布时间】:2020-05-25 12:55:06
【问题描述】:

我尝试在给定时间范围内从 pgAdmin 上的表下载数据。我有下面的代码,但它不起作用,我不知道为什么。 '''

ts, te=df['Timestamp'].min(), df['Timestamp'].max()

connection=psycopg2.connect('dbname=dbname user=user '
                        'password=password host=IP')
print(r'Connection to database is successful')
crsr=connection.cursor()
query="""SELECT * 
FROM public.scanning_lidar_ver2
ORDER BY timestamp ASC, scan_id ASC, range ASC
WHERE timestamp >= %(date_start)s AND timestamp <= %(date_end)s
"""
crsr.execute(query,
             {'date_start' : ts,
              'date_end':te})
df1= pd.DataFrame(crsr.fetchall())

'' 任何帮助深表感谢。谢谢。

【问题讨论】:

  • 您收到的错误信息是什么?
  • SyntaxError: "WHERE" 或附近的语法错误
  • order by 在 where:... WHERE timestamp &gt;= %(date_start)s AND timestamp &lt;= %(date_end)s ORDER BY timestamp ASC, scan_id ASC, range ASC

标签: python sql python-3.x psycopg2


【解决方案1】:

值得注意的是,ORDER BY 子句总是出现在SELECT 语句的END 处。您只需在您的query 中交换ORDER BY 和WHERE 原因。

如果您的列名正确,我猜您查询的其余部分看起来没有错误!祝你好运!

我怀疑你不能使用df1= pd.DataFrame(crsr.fetchall())。 试试:

exq=crsr.execute(query,
             {'date_start' : ts,
              'date_end':te})
df1=pd.DataFrame(exq.fetchall())

【讨论】:

  • 谢谢,不再有错误消息,但它返回一个空数据帧。表名和列名双重检查,它们是正确的
  • 查看编辑后的答案,但我不确定它是否有效。或者正如其他答案所说,试试 sqlalchemy!
【解决方案2】:

我建议您将 pandas 与 sqlalchemy 一起使用。 它很容易帮助使用带有 sql 的 pandas

试试这个

pd.read_sql(query_str, connection) 

【讨论】:

    猜你喜欢
    • 2016-05-28
    • 1970-01-01
    • 2017-03-14
    • 2020-07-25
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多