0

Есть ДБ с постами созданная по схеме

CREATE TABLE posts (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  title TEXT NOT NULL,
  description TEXT NOT NULL,
  content TEXT NOT NULL
);

inint_db.py код:

import sqlite3

connection = sqlite3.connect('database.db')


with open('schema.sql') as f:
    connection.executescript(f.read())

cur = connection.cursor()

cur.execute("INSERT INTO posts (title, content, description) VALUES (?, ?, ?)",
            ('First Post', 'Content for the first post', 'Description content for the first post')
            )

cur.execute("INSERT INTO posts (title, content, description) VALUES (?, ?, ?)",
            ('Second Post', 'Content for the second post', 'Description content for the second post')
            )

cur.execute("INSERT INTO posts (title, content, description) VALUES (?, ?, ?)",
            ('Third Post', 'Content for the third post', 'Description content for the third post')
            )

cur.execute("INSERT INTO posts (title, content, description) VALUES (?, ?, ?)",
            ('4 Post', 'Content for the 4 post', 'Description content for the 4 post')
            )

connection.commit()
connection.close()

Вызываю через python самый последний пост

import sqlite3


def get_db_connection():
    conn = sqlite3.connect('database.db')
    conn.row_factory = sqlite3.Row
    return conn



conn = get_db_connection()
posts = conn.execute('select MAX(id) from posts;').fetchall()
#posts = conn.execute('SELECT * FROM posts').fetchall()
conn.close()
posts=posts

Но не могу ни чего получить из этого самого последнего поста. Вот этот код вызывает ошибку:

print(posts['title'])

ошибка: File "C:\Users\windo\Desktop\Site_working_ver 0.1\HTML\test-sql.py", line 16, in print(posts['title']) TypeError: list indices must be integers or slices, not str

Может я изначально пошел не правильно. Мне надо вызвать последние три поста и разместить их на странице html с данными title description created. Помогите пожалуйста, я все ни как не пойму как это сделать

Вот здесть смотрел создание БД

5
  • 1
    fetchall возвращает список котрежей, а не словарь. покажите вашу "голову" таблицы, чтобы можно было понять под каким индексом в кортеже какой столбец находиться.
    – n1tr0xs
    22 июл 2022 в 11:39
  • @n1tr0xs Голова это что?
    – Matthew
    22 июл 2022 в 11:50
  • заголовок таблицы, в котором пишутся названия столбцов
    – n1tr0xs
    22 июл 2022 в 11:50
  • @n1tr0xs я обновил пост
    – Matthew
    22 июл 2022 в 11:52
  • @n1tr0xs это же надо было?
    – Matthew
    22 июл 2022 в 12:01

1 ответ 1

2

Есть такой вариант:

import sqlite3


def get_db_connection():
    conn = sqlite3.connect('database.db')
    conn.row_factory = sqlite3.Row
    return conn


posts_count = 3

conn = get_db_connection()
max_id = conn.execute('select MAX(id) from posts;').fetchall()[0]['MAX(id)'] # получаем id последнего поста
ids = str(tuple(range(max_id-posts_count+1, max_id+1))) # делаем список подходящих id
posts = conn.execute(f'select title, description, created from posts where id in {ids}').fetchall() # получаем последние posts_count постов
conn.close()

for post in posts:
    print(post['title'], post['description'], post['created'])

Или так:

import sqlite3


def get_db_connection():
    conn = sqlite3.connect('database.db')
    conn.row_factory = sqlite3.Row
    return conn


posts_count = 3

conn = get_db_connection()
max_id = conn.execute('select MAX(id) from posts;').fetchall()[0]['MAX(id)'] # получаем id последнего поста
posts = conn.execute(f'select title, description, created from posts where id between {max_id-posts_count+1} and {max_id}').fetchall() # получаем последние posts_count постов
conn.close()

for post in posts:
    print(post['title'], post['description'], post['created'])

Однако, это можно сделать и средствами sql:

import sqlite3


def get_db_connection():
    conn = sqlite3.connect('database.db')
    conn.row_factory = sqlite3.Row
    return conn


posts_count = 3

conn = get_db_connection()
posts = conn.execute(f'''
    SELECT * FROM (
        SELECT * FROM posts ORDER BY id DESC LIMIT {posts_count}
    ) sub
    ORDER BY id ASC
''').fetchall()
conn.close()

for post in posts:
    print(post['title'], post['description'], post['created'], sep='\t')

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.