Не работает вызов MAX(id) sqlite в python (?)
Есть ДБ с постами созданная по схеме
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. Помогите пожалуйста, я все ни как не пойму как это сделать
Вот здесть смотрел создание БД
Ответы (1 шт):
Автор решения: n1tr0xs
→ Ссылка
Есть такой вариант:
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')