Есть ДБ с постами созданная по схеме
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. Помогите пожалуйста, я все ни как не пойму как это сделать
fetchall
возвращает список котрежей, а не словарь. покажите вашу "голову" таблицы, чтобы можно было понять под каким индексом в кортеже какой столбец находиться.