Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22872

IslandT: Python Example — Create database with sqlite3

$
0
0

In this article let us create a poet database and a poet table with sqlite3 module’s and then inserted the poet entry into the table before retrieving it again from the table and displaying it on the console. Basically, sqlite3 will create a database and table, insert, delete and retrieve entries based on the SQL command thus this module itself is actually an SQL wrapper object.

The below program will create a database to keep my poet and the date on which the poet has been created. After that, I can enter the poet and save it inside the poet table! At last all those poets will get retrieved and displayed on the console.

Before you can use the sqlite3 module you will need to import it first, this is the built-in module thus all you need to do is only to import it to the python file as follows:

import datetime
import sqlite3

Besides that, you will need to import the datetime module to record the creation date of the poet.

Next the python program will create the database if it has not been created yet, create the poet table if it has not been created yet, notice that the sqlite_master table is built-in to SQLite and it contains an entry for the poet table definition if the table has been created or else the python program below will create the table for the first time.

    try:
        con = sqlite3.connect("poet.db") # starts a connection to the poet database poet.db in the current working directory, if the databse has not been created yet, then create it
        cur = con.cursor() # create a cursor

        # gets the name of the poet table if it has been created or else create it
        res = cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='poet'") 
        name_list = res.fetchall()[0][0] 
        if name_list != 'poet':
            cur.execute("CREATE TABLE poet(poet, year)")

        poet = input("Enter your poet: ") # gets the user input
        cur.execute("INSERT INTO poet VALUES(?, ?)", (poet, datetime.datetime.now())) # inserts data into the table
        con.commit()

        for row in cur.execute("SELECT poet, year FROM poet ORDER BY year"): # retrieves the data from the table
            print(row[0] + " - " + row[1]) # prints the data out row by row
        cur.close() # close cursor
        con.close() # close the connection
    except sqlite3.OperationalError:
            print("error occur")

The program will then ask the user to enter a poet and then saves it to the table, you must call con.commit() on the connection object to commit the transaction in order to insert the poet and the date into the table.

In order to avoid SQL injection attacks, you should always use the? placeholders to bind data to the query like this:-

cur.execute("INSERT INTO poet VALUES(?, ?)", (poet, datetime.datetime.now()))

At last, the program will query all the poets you have entered from the poet table and then print them out within the for loop! Each row contains an entry from the poet table. Notice that the entire codes have been wrapped within the try and except block which will print something to the user if an error occurs.


Viewing all articles
Browse latest Browse all 22872

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>