如何返回数据库中的表列表?

时间:2018-11-24 00:07:13

标签: python database sqlite

编写一个不带任何参数的名为“ get_records”的函数。有一个数据库保存在名为“ apologize.db”的文件中,该数据库包含一个名为“ foreigner”的表,该表的列为“ confirm”,“ handful”和“ chemistry”。返回包含“ foreigner”表中所有记录的列表。

import sqlite3
def get_records():
    conn = sqlite3.connect("apologize.db")
    c = conn.cursor()
    c.execute('INSERT INTO foreigner VALUES (
                    "confirm",
                    "handful",
                    "chemistry")')
    conn.commit()
    conn.close()

我在做什么错了?

3 个答案:

答案 0 :(得分:1)

您使用的是INSERT start而不是SELECT start ... 之后查看您的代码,看看该往哪里走

答案 1 :(得分:0)

根据您的问题,我相信您正在寻找与以下内容类似的内容。

def get_records():
    conn = sqlite3.connect("apologize.db")
    conn.row_factory = lambda cursor, row: row[0]
    c = conn.cursor()
    confirm_list = c.execute('SELECT confirm FROM foreigner').fetchall()
    handful_list = c.execute('SELECT handful FROM foreigner').fetchall()
    chemistry_list = c.execute('SELECT chemistry FROM foreigner').fetchall()
    conn.close()
    return [confirm_list, handful_list, chemistry_list]

def get_records():
    conn = sqlite3.connect("apologize.db")
    conn.row_factory = lambda cursor, row: row[0]
    c = conn.cursor()
    confirm_list = c.execute('SELECT confirm FROM foreigner').fetchall()
    handful_list = c.execute('SELECT handful FROM foreigner').fetchall()
    chemistry_list = c.execute('SELECT chemistry FROM foreigner').fetchall()
    conn.close()
    return [list(x) for x in zip(confirm_list, handful_list, chemistry_list)]

干杯!

答案 2 :(得分:0)

我建议您花一些时间学习an ORM like sqlalchemy,而不必再花费任何时间来学习如何解决SQL的此特定问题,而不必再花费任何时间编写SQL。

from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Foreigner(Base):
    __tablename__ = 'foreigner'
    id = Column(Integer, primary_key=True)
    confirm = Column(String(250), nullable=False)
    handful = ...
    chemistry = ...

records = Foreigner.query.all()