0% found this document useful (0 votes)
11 views

python mysql

This document provides a comprehensive guide on using Python with MySQL, focusing on database operations such as connecting to a MySQL server, creating databases and tables, inserting, fetching, updating, and deleting data. It includes code examples for each operation, demonstrating how to execute SQL commands through Python's MySQL Connector. Additionally, it covers advanced SQL clauses like WHERE, ORDER BY, LIMIT, and DROP TABLE, along with their respective syntax and usage in Python.

Uploaded by

kothitarun130301
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

python mysql

This document provides a comprehensive guide on using Python with MySQL, focusing on database operations such as connecting to a MySQL server, creating databases and tables, inserting, fetching, updating, and deleting data. It includes code examples for each operation, demonstrating how to execute SQL commands through Python's MySQL Connector. Additionally, it covers advanced SQL clauses like WHERE, ORDER BY, LIMIT, and DROP TABLE, along with their respective syntax and usage in Python.

Uploaded by

kothitarun130301
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

NALLA MALLA REDDY ENGINEERING COLLEGE, HYDERABAD

(AUTONOMOUS INSTITUION AFFILIATED TO JNTUH)


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
CS604PC MACHINE LEARNING LAB
WEEK - 2
COURSE : B.E.(CSE) SEM / YEAR : III / II
BATCH : 2020-2024

Program 2. Extract the data from database using python

Python MySQL Connector is a Python driver that helps to integrate


Python and MySQL. This Python MySQL library allows the conversion
between Python and MySQL data types. MySQL Connector API is
implemented using pure Python and does not require any third-party library.

Installation:

To install the Python-mysql-connector module, one must have


Python and PIP, preinstalled on their system. If Python and pip are already
installed type the below command in the terminal.

pip3 install mysql-connector-python

Connecting to MySQL Server

conn=mysql.connector.connect(host='localhost',user='root',password='
mysql123',db='employee')

cur=conn.cursor()

cur.execute('show databases')

output=cur.fetchall()

print(output)
conn.close()

Output:
[('information_schema',), ('employee',), ('mysql',),
('performance_schema',), ('sakila',), ('sys',), ('world',)]
Creating Database
After connecting to the MySQL, For this, we will first create a cursor()
object and will then pass the SQL command as a string to the execute()
method. The SQL command to create a database is –

CREATE DATABASE DATABASE_NAME

Creating Tables

For creating tables we will follow the similar approach of writing the SQL
commands as strings and then passing it to the execute() method of the
cursor object. SQL command for creating a table is –

CREATE TABLE
(
column_name_1 column_Data_type,
column_name_2 column_Data_type,
:
:
column_name_n column_Data_type
);

Example: Creating MySQL table using Python

Output:

Insert Data into Tables


To insert data into the MySQL table Insert into query is used.

Syntax:

INSERT INTO table_name (column_names) VALUES (data)

Example 1: Inserting Single Row

import mysql.connector

mydb = mysql.connector.connect(

host="localhost",
user="sameena",

password="mysql123",

database="employee"

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE customer (name VARCHAR(255),


address VARCHAR(255))")

sql = "INSERT INTO customer(name, address) VALUES (%s, %s)"

val = ("John", "Highway 21")

mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")

cur.execute("select * from customer")

output=cur.fetchall()

print(output)
conn.close()

Output:
1 record inserted.
[('John', 'Highway 21')]

Example 2: Inserting Multiple Rows

To insert multiple values at once, executemany() method is used. This


method iterates through the sequence of parameters, passing the current
parameter to the execute method.

Program:

import mysql.connector
mydb = mysql.connector.connect(

host="localhost",

user="selvam",

password="mysql123",

database="employee"

mycursor = mydb.cursor()

sql = "INSERT INTO customer(name, address) VALUES (%s, %s)"

val = [("ravi", "Highway 21"),("senthil","narapally 22")]

mycursor.executemany(sql, val)

mydb.commit()

mycursor.execute("select * from customer")

output=mycursor.fetchall()

print(output)
conn.close()
Output:

[('John', 'Highway 21'), ('ravi', 'Highway 21'), ('senthil', 'narapally


22'), ('ravi', 'Highway 21'), ('senthil', 'narapally 22'), ('ravi',
'Highway 21'), ('senthil', 'narapally 22')]

Fetching Data

We can use the select query on the MySQL tables in the following ways –
 In order to select particular attribute columns from a table, we write
the attribute names.

SELECT attr1, attr2 FROM table_name


 In order to select all the attribute columns from a table, we use the
asterisk ‘*’ symbol.

SELECT * FROM table_name


Example: Select data from MySQL table using Python

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="sameena",
password="mysql123",
database="employee"
)

mycursor = mydb.cursor()

mycursor.execute("select * from customer")


output=mycursor.fetchall()
print(output)

mycursor.execute("select name from customer")


output=mycursor.fetchall()
print(output)

conn.close()

Output:

[('John', 'Highway 21'), ('ravi', 'Highway 21'), ('senthil', 'narapally


22'), ('ravi', 'Highway 21'), ('senthil', 'narapally 22'), ('ravi',
'Highway 21'), ('senthil', 'narapally 22')]

[('John',), ('ravi',), ('senthil',), ('ravi',), ('senthil',),


('ravi',), ('senthil',)]

Where Clause

Where clause is used in MySQL database to filter the data as per the
condition required. You can fetch, delete or update a particular set of data in
MySQL database by using where clause.

Syntax:
SELECT column1, column2, …. columnN FROM [TABLE NAME] WHERE
[CONDITION];
Example: Where clause in MySQL using Python
Program:

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="sameena",
password="mysql123",
database="employee"
)

mycursor = mydb.cursor()

query="select * from customer where name = 'john'"


mycursor.execute(query)
output=mycursor.fetchall()
print(output)

conn.close()

Output:

[('John', 'Highway 21')]

Order By Clause

OrderBy is used to arrange the result set in either ascending or


descending order. By default, it is always in ascending order unless “DESC”
is mentioned, which arranges it in descending order. “ASC” can also be used
to explicitly arrange it in ascending order. But, it is generally not done this
way since default already does that.
Syntax:
SELECT column1, column2
FROM table_name
ORDER BY column_name ASC|DESC;

Example: Order By clause in MySQL using Python

Program:

import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="sameena",
password="mysql123",
database="employee"
)

mycursor = mydb.cursor()

mycursor.execute("select * from customer order by name desc")


output=mycursor.fetchall()
print(output)

conn.close()

Output:

[('senthil', 'narapally 22'), ('senthil', 'narapally 22'), ('senthil',


'narapally 22'), ('ravi', 'Highway 21'), ('ravi', 'Highway 21'), ('ravi',
'Highway 21'), ('John', 'Highway 21')]

Program 2 :

import mysql.connector

mydb = mysql.connector.connect(

host="localhost",

user="sameena",

password="mysql123",

database="employee"

mycursor = mydb.cursor()

mycursor.execute("select * from customer order by name asc")

output=mycursor.fetchall()

print(output)
conn.close()
Output:

[('John', 'Highway 21'), ('ravi', 'Highway 21'), ('ravi', 'Highway


21'), ('ravi', 'Highway 21'), ('senthil', 'narapally 22'), ('senthil',
'narapally 22'), ('senthil', 'narapally 22')]

Limit Clause

The Limit clause is used in SQL to control or limit the number of


records in the result set returned from the query generated. By default, SQL
gives out the required number of records starting from the top but it allows
the use of OFFSET keyword. OFFSET allows you to start from a custom row
and get the required number of result rows.

Syntax:
SELECT * FROM tablename LIMIT limit;
SELECT * FROM tablename LIMIT limit OFFSET offset;

Example: Limit Clause in MySQL using Python

Program:

import mysql.connector

mydb = mysql.connector.connect(

host="localhost",

user="sameena",

password="mysql123",

database="employee"

mycursor = mydb.cursor()

mycursor.execute("select * from customer")

output=mycursor.fetchall()

print(output)

mycursor.execute("select * from customer limit 2 offset 1")


output=mycursor.fetchall()

print(output)
conn.close()

Output:

[('John', 'Highway 21'), ('ravi', 'Highway 21'), ('senthil', 'narapally


22'), ('ravi', 'Highway 21'), ('senthil', 'narapally 22'), ('ravi',
'Highway 21'), ('senthil', 'narapally 22')]
[('ravi', 'Highway 21'), ('senthil', 'narapally 22')]

Update Data:

The update query is used to change the existing values in a database.


By using update a specific value can be corrected or updated. It only affects
the data and not the structure of the table. The basic advantage provided by
this command is that it keeps the table accurate.

Syntax:
UPDATE tablename
SET ="new value"
WHERE ="old value";

Example: Update MySQL table using Python

Program:

import mysql.connector

mydb = mysql.connector.connect(

host="localhost",

user="sameena",

password="mysql123",

database="employee"

mycursor = mydb.cursor()

mycursor.execute("select * from customer")

output=mycursor.fetchall()
print(output)

mycursor.execute("update customer set name='ramesh' where


name='john'")

mycursor.execute("select * from customer")

output=mycursor.fetchall()

print(output)
conn.close()

Output:

[('John', 'Highway 21'), ('ravi', 'Highway 21'), ('senthil', 'narapally


22'), ('ravi', 'Highway 21'), ('senthil', 'narapally 22'), ('ravi',
'Highway 21'), ('senthil', 'narapally 22')]
[('ramesh', 'Highway 21'), ('ravi', 'Highway 21'), ('senthil',
'narapally 22'), ('ravi', 'Highway 21'), ('senthil', 'narapally 22'),
('ravi', 'Highway 21'), ('senthil', 'narapally 22')]

Delete Data from Table


We can use the Delete query to delete data from the table in MySQL.
Syntax:
DELETE FROM TABLE_NAME WHERE ATTRIBUTE_NAME =
ATTRIBUTE_VALUE

Example: Delete Data from MySQL table using Python

Program:

import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="sameena",
password="mysql123",
database="employee"
)
mycursor = mydb.cursor()

mycursor.execute("select * from customer")


output=mycursor.fetchall()
print(output)

mycursor.execute("delete from customer where name='john'")

mycursor.execute("select * from customer")


output=mycursor.fetchall()
print(output)

conn.close()

Output:
[('John', 'Highway 21'), ('ravi', 'Highway 21'), ('senthil', 'narapally
22'), ('ravi', 'Highway 21'), ('senthil', 'narapally 22'), ('ravi',
'Highway 21'), ('senthil', 'narapally 22')]
[('ravi', 'Highway 21'), ('senthil', 'narapally 22'), ('ravi', 'Highway
21'), ('senthil', 'narapally 22'), ('ravi', 'Highway 21'), ('senthil',
'narapally 22')]

Drop Tables
Drop command affects the structure of the table and not data. It is
used to delete an already existing table. For cases where you are not sure if
the table to be dropped exists or not DROP TABLE IF EXISTS command is
used. Both cases will be dealt with in the following examples.
Syntax:
DROP TABLE tablename;
DROP TABLE IF EXISTS tablename;

Example 1: Drop Table in MySQL using Python

Program:

import mysql.connector

mydb = mysql.connector.connect(

host="localhost",

user="sameena",

password="mysql123",
database="employee"

mycursor = mydb.cursor()

mycursor.execute("show tables")

output=mycursor.fetchall()

print(output)

mycursor.execute("drop table customer")

mycursor.execute("show tables")

output=mycursor.fetchall()

print(output)
conn.close()

Output:
[('customer',), ('emp',)]
[('emp',)]

You might also like