UNIT – 5 BASIC DATABASE OPERATIONS AND SQL
Database Programming – Introduction - Basic Database Operations and Connect To Database
SQL - Example of using Database Adapters, Mysql - Regular To connect the python into the SQL.
Expression – Special Symbols and Characters – REs and Python. import sqlite3
conn = sqlite3.connect('test.db')
DATABASE PROGRAMMING
print "Opened database successfully";
INTRODUCTION
Database is the basis for SQL, MS SQL Server, IBM DB2,
Create a Table
Oracle, MySQL, and Microsoft Access.
To create the new table.
Python supports various databases like SQLite, MySQL,
import sqlite3
Oracle, Sybase, PostgreSQL, etc.
conn = sqlite3.connect('test.db')
Python also supports Data Definition Language (DDL), Data
print "Opened database successfully";
Manipulation Language (DML) and Data Query Statements.
conn.execute('''CREATE TABLE COMPANY
Table: Related data that consists of columns and rows.
(ID INT PRIMARY KEY NOT NULL,
Field: Small entities in a table.
NAME TEXT NOT NULL,
Record: A record is a horizontal entity in a table.
AGE INT NOT NULL,
Column: A record is a vertical entity in a table.
ADDRESS CHAR (50),
Example:
SALARY REAL);''')
print "Table created successfully";
conn.close()
V. Naresh Kumar, M.C.A., M.Phil., Page 1
Insert Operation Select Operation
To insert the record into the table. To select the particular field of record.
import sqlite3 import sqlite3
conn = sqlite3.connect('test.db') conn = sqlite3.connect('test.db')
print "Opened database successfully"; print "Opened database successfully";
conn.execute ("INSERT INTO COMPANY (ID, NAME, AGE, cursor = conn.execute("SELECT id, name, address, salary from
ADDRESS, SALARY) \ COMPANY")
VALUES (1, 'Paul', 32, 'California', 20000)"); for row in cursor:
conn.execute("INSERT INTO COMPANY print "ID = ", row[0]
(ID,NAME,AGE,ADDRESS,SALARY) \ print "NAME = ", row[1]
VALUES (2, 'Allen', 25, 'Texas', 15000)"); print "ADDRESS = ", row[2]
conn.commit() print "SALARY = ", row[3], "\n"
print "Records created successfully"; print "Operation done successfully";
conn.close() conn.close ()
V. Naresh Kumar, M.C.A., M.Phil., Page 2
Update Operation Delete Operation
To edit or update the particular record in the table. To delete the particular record in the table.
import sqlite3 import sqlite3
conn = sqlite3.connect('test.db') conn = sqlite3.connect('test.db')
print "Opened database successfully"; print "Opened database successfully";
conn.execute("UPDATE COMPANY set SALARY = 25000.00 conn.execute("DELETE from COMPANY where ID = 2;")
where ID = 1") conn.commit()
conn.commit print "Total number of rows deleted :", conn.total_changes
print "Total number of rows updated :", conn.total_changes cursor = conn.execute("SELECT id, name, address, salary from
cursor = conn.execute("SELECT id, name, address, salary from COMPANY")
COMPANY") for row in cursor:
for row in cursor: print "ID = ", row[0]
print "ID = ", row[0] print "NAME = ", row[1]
print "NAME = ", row[1] print "ADDRESS = ", row[2]
print "ADDRESS = ", row[2] print "SALARY = ", row[3], "\n"
print "SALARY = ", row[3], "\n" print "Operation done successfully";
print "Operation done successfully"; conn.close()
conn.close()
V. Naresh Kumar, M.C.A., M.Phil., Page 3
EXAMPLE OF USING DATABASE ADAPTERS 3. QTSQL
Introduction: QTSQL is a database connector.
Python offers database adapters through its modules It is used to integrate databases with PYQT5 applications.
that allow access to major databases such as, Example:
1. MySQL self.QSqlDatabase.addDatabase("QMYSQL")
2. PostgreSQL self.db.setHostName("host_name")
3. SQL Server self.db.setDatabaseName("database_name")
4. SQLite. 4. Psycopg2
Database Adapters It is the most popular PostgreSQL database adapter for the
1. PyMySQL Python programming language.
It is an open source. It was designed for multi-threaded applications.
It is a multiuser, multithreaded. Example:
Mainly used in web development. import psycopg2
Example: try:
import pymysql conn = psycopg2.connect("dbname='template1' user='dbuser'
con = pymysql.connect('localhost', 'username', host='localhost' password='dbpass'")
'password', 'db_name’') except:
print(f'Database version: {version[0]}') print "I am unable to connect to the database"
con.close() 5. SuperSQLite
2. MySQLdb It is a driver for Python.
MySQLdb is a thread-compatible interface to the MySQL It replaces the built-in newer version of SQLite.
database server. Example:
It provides the Python database API. from supersqlite import sqlite3
Example: conn = sqlite3.connect('databasefile.db')
db=_mysql.connect (host="localhost",user="username",
passwd="password",db="db_name")
V. Naresh Kumar, M.C.A., M.Phil., Page 4
MYSQL Or you can try to access the database when making the connection:
Introduction Try connecting to the database "mydatabase":
Python can be used in database applications. Example:
One of the most popular databases is MySQL. import mysql.connector
mydb = mysql.connector.connect(host="localhost",
Creating a Database
user="yourusername", password="yourpassword",
To create a database in MySQL, use the "CREATE
database="mydatabase")
DATABASE" statement:
Example:
import mysql.connector
mydb = mysql.connector.connect(host="localhost",
user="yourusername", password="yourpassword")
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
Check if Database Exists
Check if a database exist by listing all databases in your
system by using the "SHOW DATABASES" statement:
Example:
import mysql.connector
mydb = mysql.connector.connect(host="localhost",
user="yourusername", password="yourpassword")
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
V. Naresh Kumar, M.C.A., M.Phil., Page 5
REGULAR EXPRESSION SPECIAL SYMBOLS AND CHARACTERS
Introduction Metacharacters
It is a sequence of characters that forms a search pattern. [] - A set of characters
Regular Expression can be used to check if a string contains ^ - Starts with
the specified search pattern. $ - Ends with
Regular Expression Module * - Zero occurrences
Python has a built-in package called re. | - Either or
re can be used to work with Regular Expressions. () - group
Import the re module:
import re Special Sequences - A special sequence is a \ followed by one of the
Example: characters.
//Check if the string starts with "The" and ends with "Spain": \A - Return the characters are at beginning of the string.
import re \b - Return the beginning & end of the word in the string.
txt = "The rain in Spain" \d - Returns the string contains digits (from 0-9).
x = re.search("^The.*Spain$", txt) \D - Returns the string does not contain digits (from 0-9).
if x: \s - Returns the string contains a white space character.
print("YES! We have a match!") \S - Returns the string does not contain a white space.
else:
print("No match")
SPECIAL SYMBOLS AND CHARACTERS
V. Naresh Kumar, M.C.A., M.Phil., Page 6
Sub()
Sets Replaces the matches.
A set is a set of characters inside a pair of square brackets []. Example:
[arn] - Returns a match where specified characters. import re
[a-n] - Returns a match for any lower case character. txt = "The rain in Spain"
[0-9] - Returns a match for any digit between 0 and 9. x = re.sub("\s", "9", txt)
Findall() print(x)
Returns a list containing all matches.
Example:
import re
txt = "The rain in Spain"
x = re.findall("ai", txt)
print(x)
Split()
Returns a list where the string has been split.
Example:
import re
txt = "The rain in Spain"
x = re.split("\s", txt)
print(x)
V. Naresh Kumar, M.C.A., M.Phil., Page 7
REs AND PYTHON group() - Return the string matched by the RE.
The Backslash Plague start() - Return the starting position of the
\section - Text string to be matched match.
\\section - Escaped backslash for re.compile () end() - Return the ending position of the
\\\\section - Escaped backslashes for a string m;atch
Literal span() - Return a tuple containing the (start,
Performing Matches end) positions of the match
match() - Determine if the RE matches at the Example:
beginning. import re
of the string. txt = "The rain in Spain"
search() - Scan through a string, looking for any x = re.split("\s", txt)
location print(x)
where this RE matches.
findall() - Find all substrings where the RE
matches, and
returns them as a list.
finditer() - Find all substrings where the RE
matches, and returns them as
an iterator.
V. Naresh Kumar, M.C.A., M.Phil., Page 8