Spaces:
Running
Running
Create database.py
Browse files- database.py +43 -0
database.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sqlite3
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
DATABASE = 'database.db'
|
| 5 |
+
|
| 6 |
+
def create_table():
|
| 7 |
+
with sqlite3.connect(DATABASE) as db:
|
| 8 |
+
cursor = db.cursor()
|
| 9 |
+
cursor.execute('''
|
| 10 |
+
CREATE TABLE IF NOT EXISTS news (
|
| 11 |
+
id INTEGER PRIMARY KEY,
|
| 12 |
+
title TEXT NOT NULL,
|
| 13 |
+
source TEXT NOT NULL,
|
| 14 |
+
published TEXT NOT NULL,
|
| 15 |
+
url TEXT NOT NULL,
|
| 16 |
+
summary TEXT NOT NULL,
|
| 17 |
+
content TEXT NOT NULL
|
| 18 |
+
)
|
| 19 |
+
''')
|
| 20 |
+
db.commit()
|
| 21 |
+
|
| 22 |
+
def insert_news(title, source, published, url, summary, content):
|
| 23 |
+
with sqlite3.connect(DATABASE) as db:
|
| 24 |
+
cursor = db.cursor()
|
| 25 |
+
cursor.execute('''
|
| 26 |
+
INSERT INTO news (title, source, published, url, summary, content)
|
| 27 |
+
VALUES (?,?,?,?,?,?)
|
| 28 |
+
''', (title, source, published, url, summary, content))
|
| 29 |
+
db.commit()
|
| 30 |
+
|
| 31 |
+
def get_all_news():
|
| 32 |
+
with sqlite3.connect(DATABASE) as db:
|
| 33 |
+
cursor = db.cursor()
|
| 34 |
+
cursor.execute('SELECT * FROM news')
|
| 35 |
+
return cursor.fetchall()
|
| 36 |
+
|
| 37 |
+
def get_news_by_id(id):
|
| 38 |
+
with sqlite3.connect(DATABASE) as db:
|
| 39 |
+
cursor = db.cursor()
|
| 40 |
+
cursor.execute('SELECT * FROM news WHERE id =?', (id,))
|
| 41 |
+
return cursor.fetchone()
|
| 42 |
+
|
| 43 |
+
create_table()
|