如何将查询结果从QuestDB获取到数据帧中?

2024-06-12 21:32:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python中的psycopg2连接到QuestDB,并运行select * from my_table,但列名是序列号:

import psycopg2
import pandas as pd

dataframe = pd.DataFrame()
try:
    connection = psycopg2.connect(user="myuser",
                                  password="mypassword",
                                  host="127.0.0.1",
                                  port="8812",
                                  database="qdb")
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM my_table")

    dataframe = pd.DataFrame(cursor.fetchall())

except (Exception, psycopg2.Error) as error:
    print("Error while connecting to QuestDB", error)
finally:
    if (connection):
        cursor.close()
        connection.close()
        print("QuestDB connection closed")
print(dataframe)

不带列名的行如下所示:

                           0    1  2
0 2021-08-23 12:15:43.582771  100  1
1 2021-08-23 12:15:46.529379    1  2
2 2021-08-23 12:15:46.656823    1  2
3 2021-08-23 12:15:46.662040    1  2
4 2021-08-23 12:15:46.805505    1  2
5 2021-08-23 12:15:46.807359    1  2
6 2021-08-23 12:15:48.631560    1  2
7 2021-08-23 12:16:08.120285    6  3

Tags: importdataframeclosemyastableerrorconnection
1条回答
网友
1楼 · 发布于 2024-06-12 21:32:55

问题是fetchall获取游标中每一行的结果,要正确返回表结果,请使用read_sql_query

import psycopg2
import pandas as pd

dataframe = pd.DataFrame()
try:
    connection = psycopg2.connect(user="admin",
                                  password="quest",
                                  host="127.0.0.1",
                                  port="8812",
                                  database="qdb")
    cursor = connection.cursor()
    dataframe = pd.read_sql_query("select * from my_table",connection)

except (Exception, psycopg2.Error) as error:
    print("Error while connecting to QuestDB", error)
finally:
    if (connection):
        cursor.close()
        connection.close()
        print("QuestDB connection closed")
print(dataframe)

这将返回:

                    timestamp  event  origin
0  2021-08-23 12:15:43.582771    100       1
1  2021-08-23 12:15:46.529379      1       2
2  2021-08-23 12:15:46.656823      1       2
3  2021-08-23 12:15:46.662040      1       2
4  2021-08-23 12:15:46.805505      1       2
5  2021-08-23 12:15:46.807359      1       2
6  2021-08-23 12:15:48.631560      1       2
7  2021-08-23 12:16:08.120285      6       3
8  2021-08-23 12:16:58.080873      6       3
9  2021-08-23 12:16:58.081986      6       3
10 2021-08-23 12:16:58.084083      1       3

相关问题 更多 >