How to setting up a SQLite database for data storage?

By Sajid, 6 months ago
  • Bookmark
0

store data into SQLite database and display the data

Sqlite
Python
1 Answer
0

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')]

Your Answer

Webinars

More webinars

Related Discussions

Running random forest algorithm with one variable

View More
We're Online!

Chat now for any query