0% found this document useful (0 votes)
1 views40 pages

M4 Python SQL

The document provides a comprehensive guide on using Python's SQLite3 module for database operations, including connecting to a database, creating tables, and performing CRUD operations (Create, Read, Update, Delete). It details the necessary methods such as connect(), cursor(), execute(), and close(), along with example code snippets for each operation. Additionally, it covers the installation of MySQL connector and basic commands for managing databases using XAMPP and Python.

Uploaded by

Saraswathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views40 pages

M4 Python SQL

The document provides a comprehensive guide on using Python's SQLite3 module for database operations, including connecting to a database, creating tables, and performing CRUD operations (Create, Read, Update, Delete). It details the necessary methods such as connect(), cursor(), execute(), and close(), along with example code snippets for each operation. Additionally, it covers the installation of MySQL connector and basic commands for managing databases using XAMPP and Python.

Uploaded by

Saraswathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Contents:

 Python SQLite
 The SQLite3 module
 SQLite Methods:
 connect, cursor, execute, close
 Connect to Database:
 Create Table;
 Operations on Tables:
 Insert, Select, Update, Delete, Drop Records
 Python SQLite3 module is used to integrate the SQLite
database with Python.
 It provides a straightforward and simple-to-use
interface for interacting with SQLite databases.
SQLite Methods
 connect():
 To use SQLite3 in Python, first we have to import the sqlite3
module and then create a connection object.
 Connection object allows to connect to the database and will
let us execute the SQL statements.
 Creating Connection object using the connect() function:
 This will create a new file with the name ‘mydatabase.db’.
Syntax:
import sqlite3
con = sqlite3.connect('mydatabase.db‘)
 cursor()
 To execute SQLite statements in Python, we need a cursor object.
 We can create it using the cursor() method.
 The SQLite3 cursor is a method of the connection object.
 To execute the SQLite3 statements,
 should establish a connection at first and
 then create an object of the cursor
 Using the connection object as follows:
Syntax:
import sqlite3
con = sqlite3.connect('mydatabase.db‘)
cursorObj = con.cursor()

Cursor object is used to manage and control the execution of SQL


queries and the retrieval of data from a database.
It acts as an intermediary between the Python application and the
database.
Providing a structured way to interact with the database.
 execute():
 Once the database and connection object is created,
 we can create a table using CREATE TABLE statement.
 Then we execute the CREATE TABLE statement by calling
cur.execute()

Syntax:
import sqlite3
con = sqlite3.connect('mydatabase.db‘)
cursorObj = con.cursor()
cursorObj.execute(''' CREATE TABLE movie(title text,
year int, score real) ''' )
 close():
 Once we are done with our database, it is a good practice
to close the connection.
 We can close the connection by using the close()
method.
 To close a connection, use the connection object and call
the close() method as follows:

con = sqlite3.connect('mydatabase.db') #program statement

con.close()
SQLite database operations
 Creating and connecting to Database
 When you create a connection with SQLite, that will
create a database file automatically if it doesn’t already
exist.
 This database file is created on disk with the connect
function.
 Following Python code shows how to connect to an
existing database.
 If the database does not exist, then it will be created
and finally a database object will be returned.
 execute() : This method accepts a MySQL query as a parameter
and executes the given query.

 fetchall(): This method retrieves all the rows in the result set
of a query and returns them as list of tuples.
 (If we execute this after retrieving few rows it returns the remaining
ones)

 fetchone(): This method fetches the next row in the result of a


query and returns it as a tuple.

 fetchmany(): This method is similar to the fetchone() but, it


retrieves the next set of rows in the result set of a query, instead
of a single row.
Steps to remember:
 Import Module
 Create connection using connect()
 Create cursor object to execute statement
 Use execute method to perform query statement
 Display the content
 Close the cursor object
 Finally, close the connection
 To perform operation we have to use execute()
 To get single record we have to use fetchOne()
 To get all records we have to use fetchAll()
Command Prompt
 Login as Test / User#123
 Open Command Prompt as administrator
 Install mysql connector
> pip install mysql.connector

 Type > python


 Check & note down the Version
>>> import pandas
>>> import numpy
>>> import matplotlib
>>>import mysql.connector
>>>exit(0)
>pip install mysql.connector
>python
>>> import mysql.connector
>>> exit(0)
Open XAMPP Control panel
 Open Command prompt install >> pip install mysql.connector
 Step 1: Open XAMPP Control Panel
 Step 2: Start Apache & MySQL module
 Step 3: Open the http://localhost:80/phpmyadmin
 Step 4: Click on Home
 Step 5: Create Database “Employee”
 Step 6: Click on Employee
 Step 7: Create a table Emptab
 Step 8: Add 3 fields : eno, ename, esal
 Step 4: Insert the values: either manually or through SQL query
 Step 8: Write python code to
 Create Database “StudentDB”
 Click on studentDB,
 Create table students
 Insert 5 fields Reg No, Name, M1,M2,M3
 Add values to it
Code Test Connection:
import mysql.connector
conn=mysql.connector.connect(host="localhost",us
er="root",password="",database="studentDB",buffer
ed=True)
cursor=conn.cursor()
print(conn)
Create Database
import mysql.connector
conn=mysql.connector.connect(host="localhost",us
er="root",password="")
mycursor = conn.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
Inserting data
import mysql.connector
conn=mysql.connector.connect(host="localhost",user="
root",password="",database="students",buffered=True)
cursor=conn.cursor()

st="insert into student values('%d','%s','%d','%d','%d')"


arg=(121,”John”,89,87,78)
cursor.execute(st % arg)
conn.commit()
print ('1 row inserted')
Inserting data using function
import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",p
assword="",database="students",buffered=True)
cursor=conn.cursor()
def insert_rows(regno,name,ml,m2,m3):
st="insert into student values('%d','%s','%d','%d','%d')"
arg=(regno,name,ml,m2,m3)
cursor.execute(st % arg)
conn.commit()
print ('1 row inserted')
while True:
print("\t\t\t\n student information")
print("l. enter student information")
print("2.display details of all student")
print("3.delete a student")
print("4.exit")
ch=int(input("enter your choice"))
if(ch==1):
regno=int (input ("enter student regno:"))
name=input ("enter student name:")
ml=int (input ("enter subject 1 marks:"))
m2=int (input ("enter subject 2 marks:"))
m3=int (input ("enter subject 3 marks:"))
insert_rows(regno,name,ml, m2,m3)
elif ch==4:
break
else:
print ("invaild choice")
cursor.close()
conn.close()
Display using function
Create Table
 To create a table in SQLite3, you can use the Create Table query in the
execute() method.
 Consider the following steps:
1. Create a connection object.
2. From the connection object, create a cursor object
3. Using the cursor object,
call the execute method with create table query as the parameter.

import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
cursorObj.execute('''CREATE TABLE movie(title text, year int, score real)''')
con.commit()
con.close()

 The commit() method saves all the changes we make.


Insert in Table
 To insert data in a table, we use the INSERT INTO statement.
 Consider the following line of code:

import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
cursorObj.execute('''CREATE TABLE movie(title text, year int,
score real)''')
cursorObj.execute('''INSERT INTO movie VALUES ("Titanic",1997,
9.5)''')
con.commit()
con.close()
Update Table
 To update the table:
 First, create a connection,
 create a cursor object using the connection and
 finally use the UPDATE statement in the execute() method.

 Suppose that we want to update the score with the movie title Dil.
 For updating, we will use the UPDATE statement and for the movie whose title
equals Dil. We will use the WHERE clause as a condition to select this
employee.
 Consider the following code:

import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
cursorObj.execute("UPDATE MOVIE SET SCORE=10 WHERE TITLE='Dil' ")
con.commit()
con.close()
Select statement
 You can use the select statement to select data from a
particular table.
 If you want to select all the columns of the data from a
table, you can use the asterisk (*).
 The syntax for this will be as follows:
cursorObj.execute("SELECT * FROM movie ")
OR
cursorObj.execute( "select column1, column2
from movie ")
Fetch all data
 To fetch the data from a database, we will execute the SELECT statement and
then will use the fetchall() method of the cursor object to store the values into a
variable.
 After that, we will loop through the variable and print all values.
 The code will be like this:

import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()

cursorObj.execute("SELECT * FROM movie ")


records=cursorObj.fetchall()

for row in records:


print(row)

con.commit()
con.close()
Delete
 In SQLite database we use the following syntax to delete data from a
table:
 Import the required module.
 Create a connection object with the database using to connect().
 Create a Cursor object by calling the cursor().
 Finally, use execute() method by passing a DELETE statement as a parameter to it.

import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()

#Deleting
cursorObj.execute("Delete from movie where title='Titanic' ")
con.commit()
con.close()
Drop table
 You can drop/delete a table using the DROP statement.
 The syntax of the DROP statement is as follows:

import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()

cursorObj.execute(" DROP TABLE IF EXISTS MOVIE ")

con.commit()
con.close()
Connection using MySql

 import mysql.connector
 conn=mysql.connector.connect(host="localhost",user
="root",password="",database="students",buffered=Tr
ue)
 cursor=conn.cursor()
Program to demonstrate a database operations-
create, insert, select, update, delete and drop
import sqlite3 #importing the module
con = sqlite3.connect('mydatabase.db') #create connection object
cursorObj = con.cursor() #crete a cursor

#creating the table


cursorObj.execute('''CREATE TABLE movie(title text, year int, score real)''')

#inserting the data


cursorObj.execute('''INSERT INTO movie VALUES ("Titanic",1997, 9.5)''')
cursorObj.execute('''INSERT INTO movie VALUES ("KGF",2020, 9.1)''')
cursorObj.execute('''INSERT INTO movie VALUES ("Dil",1990, 8.5)''')

print("Initial Data...") #Print the Initial Data


cursorObj.execute("SELECT * FROM movie ")
[print(row) for row in cursorObj.fetchall()]
#Updating
cursorObj.execute("UPDATE MOVIE SET SCORE=10 WHERE TITLE='Dil' ")

print("After updating...") #Print the after updating

cursorObj.execute("SELECT * FROM movie ")


[print(row) for row in cursorObj.fetchall()]

#Deleting
cursorObj.execute("Delete from movie where title='Titanic' ")
print("After deleting...") #Print the after Deleting

cursorObj.execute("SELECT * FROM movie ")


[print(row) for row in cursorObj.fetchall()]

#Drop the table


cursorObj.execute(" DROP TABLE IF EXISTS MOVIE ")

con.commit() #commit changes in the database


con.close() #close the connection
Insert Command execution
Search Employee by ID
List all Employee
 3.9  3.12 Issues:
38,39
 32  36
 35  34 26,20

 37  41,40,28() 31,41,42
 29  43
33,36
 27  25
 23  24
 19  22
 18
Key points to remember:
 Step 1: Check python version
 Open Command prompt run as administrator
 Type python
 Check the version
 Step 2: Open Xampp control panel
 Enable Apache & Mysql
 Open mysql admin panel using link :
localhost:80/phpmyadmin
 Create respective Database, table and fields
 Step 3: Python SQL Code
 Open IDLE script mode
 Write the code & save the file
 Using Run Module option execute the code

 Step 4: Alternative way to execute the python sql code


 Open Notepad
 Type python code
 Save the file as filename.py
 Copy the file location
 Open command prompt as a administrator
 >cd.. #To go back
 >cd user* # To set User folder …. And so on
 Using cd command set the path in command prompt & then execute the python code
using
 >python filename.py

You might also like