create_users_table = """ CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER, gender TEXT, nationality TEXT ); """
create_posts_table = """ CREATE TABLE IF NOT EXISTS posts( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, description TEXT NOT NULL, user_id INTEGER NOT NULL, FOREIGN KEY (user_id) REFERENCES users (id) ); """
create_posts = """ INSERT INTO posts (title, description, user_id) VALUES ("Happy", "I am feeling very happy today", 1), ("Hot Weather", "The weather is very hot today", 2), ("Help", "I need some help with my work", 2), ("Great News", "I am getting married", 1), ("Interesting Game", "It was a fantastic game of tennis", 5), ("Party", "Anyone up for a late-night party today?", 3); """
select_posts = "SELECT * FROM posts" posts = execute_read_query(connection, select_posts)
for post in posts: print(post)
输出结果:
1 2 3 4 5 6
(1, 'Happy', 'I am feeling very happy today', 1) (2, 'Hot Weather', 'The weather is very hot today', 2) (3, 'Help', 'I need some help with my work', 2) (4, 'Great News', 'I am getting married', 1) (5, 'Interesting Game', 'It was a fantastic game of tennis', 5) (6, 'Party', 'Anyone up for a late-night party today?', 3)
(1, 'James', 'I am feeling very happy today') (2, 'Leila', 'The weather is very hot today') (2, 'Leila', 'I need some help with my work') (1, 'James', 'I am getting married') (5, 'Elizabeth', 'It was a fantastic game of tennis') (3, 'Brigitte', 'Anyone up for a late night party today?')
再如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
select_posts_comments_users = """ SELECT posts.description as post, text as comment, name FROM posts INNER JOIN comments ON posts.id = comments.post_id INNER JOIN users ON users.id = comments.user_id """
for posts_comments_user in posts_comments_users: print(posts_comments_user)
输出:
1 2 3 4 5 6
('Anyone up for a late night party today?', 'Count me in', 'James') ('I need some help with my work', 'What sort of help?', 'Elizabeth') ('I am getting married', 'Congrats buddy', 'Leila') ('It was a fantastic game of tennis', 'I was rooting for Nadal though', 'Mike') ('I need some help with my work', 'Help with your thesis?', 'Leila') ('I am getting married', 'Many congratulations', 'Elizabeth')
column_names = [description[0] for description in cursor.description] print(column_names)
输出:
1
['post', 'comment', 'name']
下面的代码,演示了含WHERE的SQL语句查询结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
select_post_likes = """ SELECT description as Post, COUNT(likes.id) as Likes FROM likes, posts WHERE posts.id = likes.post_id GROUP BY likes.post_id """
('The weather is very hot today', 1) ('I need some help with my work', 1) ('I am getting married', 2) ('It was a fantastic game of tennis', 1) ('Anyone up for a late night party today?', 2)
更新
有了前面的操作经验,再执行UPDATE,就轻车熟路了。
先查询posts中id=2的记录:
1 2 3 4 5 6
select_post_description = "SELECT description FROM posts WHERE id = 2"