World's Best AI Learning Platform with profoundly Demanding Certification Programs
Designed by IITians, only for AI Learners.
Designed by IITians, only for AI Learners.
New to InsideAIML? Create an account
Employer? Create an account
Python standard library, sqlite3, which allows us to work with SQLite databases
Example :
By executing the following code, we will create a new SQLite database inside the directory and store two example movie reviews:
>>> import sqlite3 >>> import os >>> conn = sqlite3.connect('reviews.sqlite') # create a connection >>> c = conn.cursor() # create a cursor >>> c.execute('CREATE TABLE review_db (review TEXT, sentiment INTEGER, date TEXT)') # create a new database table >>> str1= 'I love this movie' >>> c.execute("INSERT INTO review_db (review, sentiment, date) VALUES (?, ?, DATETIME('now'))", (str1, 1)) >>> str2= 'I disliked this movie' >>> c.execute("INSERT INTO review_db (review, sentiment, date) VALUES (?, ?, DATETIME('now'))", (str2, 0)) # insert values into table >>> conn.commit() # save the change >>> conn.close() # close the connection
Display data
To fetch all rows in the database table that have been committed between the beginning of the year 2015 and today:
>>> conn = sqlite3.connect('reviews.sqlite') >>> c = conn.cursor() >>> c.execute("SELECT * FROM review_db WHERE date BETWEEN '2015-01-01 00:00:00' AND DATETIME('now')") >>> results = c.fetchall() >>> conn.close() >>> print(results) [('I love this movie', 1, '2015-06-02 16:02:12'), ('I disliked this movie', 0, '2015-06-02 16:02:12')]