Coding Python with SQLite DB

  • March 9, 2020

Coding Python with SQLite DB

 

Coding Python with SQLite DB

Got a homework assignment on Python is Easy coding class. The homework assignment can be fulfilled using 2 different method, the first one is uploading some code sample, and the other one is to write it in a blog. It turn out that i have started a blog and haven’t look at it for a very long time 😞, so this might be the right time to start to write again. But, actually this is not orginally my writing. This is just a rewrite from python3 documentation but with my own code just to help me make sure that i have the correct understanding with the documentation python3 have.

Okay, so this time i will try to write some code sample using python to connect and work with SQLite database, i hope this will help me or others that try to learn python.

The library used to connect to a SQLite Database called ‘sqlite3’.
But before that, first let’s talk about why we need to connect to a database and specially why using SQLite.

When we start to code, sometimes or in many times we need to save the data we are working on in some sort of media. We might choose a text file for a very simple data recording media, but when we work with more complex data or with simple data but large number of it, we are going to need a more advance system to do that. This is the time when a database comes in handy.
A database with its rows and columns let us save and record data in a way that we can do more complex actions with that data. There are a lot of database system out there like MySQL, PostgreSQL, Oracle, SQLServer, and more, so the next question is why we should choose SQLite?

From python documentation i quote
“SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It’s also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.”

From this paragraph i understand that SQLite is lightweight and can be used as a prototyping tools in the development process of an application lifecycle, and later on this chunk of code can then be replace when the developer needs to port their application to use a larger database.

So, how can we use SQLite Database in our python code?

First, we import the class in the library

import sqlite3

Next, we create a ‘Connection’ object from the database we want to connect with, the format to do that is like this “ConnectionVariableName = sqlite3.connect(‘database_name.db’)”
this time i am going to use database named sample.db as our database

Sumber : https://aziritt.net/