Python Database Handling
Introduction
In this chapter, you will learn to use database with python.
Database
A database is an organized collection of data, generally stored and accessed electronically from a computer system. Where databases are more complex they are often developed using formal design and modeling techniques.
Python language supports many database servers as:
- MySQL
- PostgreSQL
- Microsoft SQL Server
- Oracle
- SQLite
Note
We can work with any database without changing code because mostly the Database works with the same method for handling databases that give the flexibility to change the database any time without any code change.
Python Also Support various databases .you can see support database to python.
- Now today I will tell database handling with the SQLite database.
- SQLite database is light weighted and it can easily embed with embedded applications.
- Now we are going to implement a database using python.
- SQLite library are already in-built with python.
- Now open Command Prompt and open python terminal for handling database operations.
- Now we create a database using the below code when we write in python terminal.
- import sqlite3
- conn = sqlite3.connect('article.db')
- c=conn.cursor()
- conn.close
- Now we create a table in article.db database as below code:
- import sqlite3
- conn = sqlite3.connect('article.db')
- c=conn.cursor()
- c.execute("create table example(Software VARCHAR, Version Real,Price Real )")
- Now we inserting the data into an example table as below.
- c.execute("Insert into example Values('Python',3.4,'100')")
- c.execute("Insert into example Values('Adobe',10.2,'1000')")
- c.execute("Insert into example Values('Office',16,'1000')")
- Now we read the data from databse using code:
- sql = "select * from example"
- for row in c.execute(sql):
- print("Software: "+row[0]
- print("Version: "+str(row[1])
- print("Price: "+str(row[2]))
- Now we Insert data dynamically in a database using the make method in python:
- def dynamic_data():
- soft = input("Write Software Name : ")
- version = input("Write Versio : ")
- Price= input("Write Price")
- c.execute("insert into example(Software,Version,Price) values(?,?,?)" ,(soft,version,Price))
- conn.commit()
- dynamic_data()
- Now we take another database handling with update the data in the database,
- sql="update example set Version = 3.5 where Software = 'Python'"
- c.execute(sql)
- sql = "select * from example"
- for row in c.execute(sql):
- print(row)
- Another Example of perform detele operation on database:
- sql="delete from example where Software = 'Python'"
- c.execute(sql)
- sql = "select * from example"
- for row in c.execute(sql):
- print(row)
Conclusion
From the next chapter onwards will see some implementations of Python into some real-world applications.
Author
Neeraj Kumar
0
8.1k
2.3m