0

我正在尝试从 Firebird 数据库中的表中获取数据。到目前为止,我已经成功地建立了连接并获得了表名。在此处的其他一些帖子之后,我已经设法使用光标函数“选择”(无论这意味着什么)我想要读取的数据库,但我无法检索信息并在 Pandas 中使用它,即我想要的是。

这是我的代码,我希望你能帮助我解决这个问题:

#Connection is made
con=fdb.connect(dsn=r'C:\table.FDB',user='SYSD', password='key')

#I don't know what this is for, but it helps me get the table names and somehow I think I'm getting closer.

schema1=fdb.schema.Schema()
schema1.bind(con)
for i in range(len(schema1.tables)):
    print(schema1.tables[i].name)
    
#This I got it from this post that said it would retrieve the data, but I just don't know how to get it: https://stackoverflow.com/questions/64826318/extract-data-from-a-firebird-database-with-python-fdb-module 

cur1=con.cursor()
cur1.execute('select * from "INVE04"')

#I get the following:
<fdb.fbcore.Cursor at 0x2b213a0fe20>

接下来我应该怎么做才能读取数据?我不熟悉 Firebird,所以查阅文档我找不到任何方法或方式来读取/提取/使用每个表中的数据。我在这里走对了吗?

4

1 回答 1

0

Firebird FDB 驱动程序实现了Python DB API 2.0 (PEP-249)。您检索行的方式已在此 API 中标准化,也记录在FDB 文档中。具体来说,执行 SQL 语句显示了处理查询结果的 3 种不同方式:

import fdb

con = fdb.connect(dsn='/temp/test.db', user='sysdba', password='masterkey')

cur = con.cursor()
SELECT = "select name, year_released from languages order by year_released"

# 1. Using built-in support for iteration protocol to iterate over the rows available from the cursor,
# unpacking the resulting sequences to yield their elements (name, year_released):
cur.execute(SELECT)
for (name, year_released) in cur:
    print '%s has been publicly available since %d.' % (name, year_released)
# or alternatively you can take an advantage of cur.execute returning self.
for (name, year_released) in cur.execute(SELECT):
    print '%s has been publicly available since %d.' % (name, year_released)

# 2. Equivalently using fetchall():
# This is potentially dangerous if result set is huge, as the whole result set is first materialized
# as list and then used for iteration.
cur.execute(SELECT)
for row in cur.fetchall():
    print '%s has been publicly available since %d.' % (row[0], row[1])

# 3. Using mapping-iteration rather than sequence-iteration:
cur.execute(SELECT)
for row in cur.itermap():
    print '%(name)s has been publicly available since %(year_released)d.' % row

简而言之,您可以迭代游标本身(序列迭代,选项 1),您可以使用fetchall()(选项 2)将所有行提取到列表中,或者您可以使用itermap()(映射迭代,选项 3)。

还有其他选项(例如重复调用fetchone(),或使用 批量获取fetchmany())。

于 2021-06-04T09:25:11.403 回答