Download presentation
Presentation is loading. Please wait.
Published byS.Anitha S Modified over 4 years ago
1
PYTHON MYSQL CONNECTIVITY BY NANDINI DAS
2
Lecture15 2.PYTHON MYSQL CONNECTOR/PYTHON 1. Install Python 2. Install MySQL 3. Open Command prompt 4. Switch on internet connection 5. Type pip install mysql-connector-python and execute 6. Open python IDLE 7. import mysql.connector Remember to check your Python version mysql-connector- python-2.1.7-py3.4- windows-x86-64bit.msi
3
Lecture15 2.PYTHON MYSQL CONNECTOR/PYTHON Commonly, Python applications will need to access a database of some sort. The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard. You must download a separate DB API module for each database MySQL alone has the following interface modules to choose: MySQL for Python (import MySQLdb) MySQL Connector/Python (import mysql.connector) etc So which module do you choose? Well, as far as code-writing goes, it probably won’t make that much of a difference… Download and install MySQL Connector/Python https://dev.mysql.com/downloads/connector/python/ Remember to check your Python version mysql-connector- python-2.1.7-py3.4- windows-x86-64bit.msi
4
Lecture15 2.PYTHON ESTABLISHING & MAKING A CONNECTION Before we can access data in a database, we must open a connection to the MySQL server. The connect() creates a connection to the MySQL server and returns a Connection object. close() – close connection. commit() – commit pending transaction (if supported). rollback() – if supported by db, roll back to start of pending transaction. cursor() – return a Cursor object for the connection. import mysql.connector... conn = mysql.connector.connect(user=my_user, password=my_password, host=my_host, database=my_database) ParameterDescription hoststuddb-mysql.fos.auckland.ac.nz usernameYour UPI passwordPassword given from email Database namestu_YOURUPI_COMPSCI_280_C_S2_2017 Use these information to connect to your own database
5
Lecture15 2.PYTHON CREATING CURSOR OBJECT Create a cursor object that allows Python code to execute database command. They are bound to the connection for the entire lifetime and all the commands are executed in the context of the database session wrapped by the connection. The following attributes should be available: description – a description of the cursor with up to seven fields. rowcount – number of rows produced by last execute method (-1 by default). Methods: close(): close the cursor object cursor = conn.cursor()
6
import mysql.connector my_user = "" my_password = "" my_host = "studdb-mysql.fos.auckland.ac.nz" my_database = "stu_kng001_COMPSCI_280_C_S2_2016" try: conn = mysql.connector.connect(user=my_user, password=my_password, host=my_host, database=my_database) cursor = conn.cursor() print("Connected") except: print("Error: unable to fetch data") cursor.close() conn.close() Lecture15 2.PYTHON EXAMPLE 1 Steps: Connect the MySQL Database server Create a cursor object
7
2.PYTHON EXECUTING A SQL QUERY Execute sql queries using the execute() method associated with the cursor object. Syntax: prepare and execute an operation with parameters where the second argument may be a list of parameter sequences. Examples: Count the number of employees in the EMPLOYEES table: c.execute[many](op, [params]) sql = "SELECT COUNT(*) FROM EMPLOYEES“ conn = mysql.connector.connect(user=my_user, password=my_password, host=my_host, database=my_database) cursor = conn.cursor() cursor.execute(sql) result = cursor.fetchone() print(result)
8
2.PYTHON FETCH DATA FROM DATABASE Multiple ways to retrieve data: fetchall() Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples) fetchmany(size) Fetch the next set of rows of a query result, returning a sequence of sequences. It will return number of rows that matches to the size argument. fetchone() Fetch the next row of a query result set, returning a single sequence or None when no more data is available.
9
9 2.PYTHON EXAMPLE 3: One record: Multiple records: Print the last name and surname from the EMPLOYEES table: cursor.execute(sql) rows = cursor.fetchall() for row in rows: fname = row[0] lname = row[1] print( "%s, %s" % (fname, lname)) SUSAN, BROWN JIM, KERN MARTHA, WOODS ELLEN, OWENS HENRY, PERKINS CAROL, ROSE DAN, SMITH FRED, CAMPBELL PAULA, JACOBS NANCY, HOFFMAN sql = "SELECT COUNT(*) FROM EMPLOYEES“ cursor.execute(sql) result = cursor.fetchone() print(result) 10 a list of tuples
10
#CONNECT import mysql.connector mydb=mysql.connector.connect(host="loc alhost",user="root",passwd="12345")
11
# CHECK CONNECTION import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",pass wd="12345") if mydb.is_connected()==True: print("connection ok") else: print("error connecting to mysql database")
12
#CREATE DATABASE import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",p asswd="12345") mycursor=mydb.cursor() mycursor.execute("CREATE DATABASE SCHOOL")
13
# SHOW DATABASE import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",pass wd="12345") mycursor=mydb.cursor() mycursor.execute("SHOW DATABASE") for x in mycursor: print (x)
14
Lecture15 # CREATE TABLE import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345 ",database="student") mycursor=mydb.cursor() mycursor.execute("CREATE TABLE FEES (ROLLNO INTEGER(3),NAME VARCHAR(20),AMOUNT INTEGER(10));")
15
Lecture15 # SHOW TABLES import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",pass wd="12345",database="student") mycursor=mydb.cursor() mycursor.execute("SHOW TABLES") for x in mycursor: print(x)
16
Lecture15 #DESCRIBE TABLE import mysql.connector mydb=mysql.connector.connect(host="localhost",u ser="root",passwd="12345",database="student") mycursor=mydb.cursor() mycursor.execute("DESC STUDENT") for x in mycursor: print(x)
17
Lecture15 # INSERT import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="studen t") mycursor=mydb.cursor() r=int(input("enter the rollno")) n=input("enter name") m=int(input("enter marks")) mycursor.execute("INSERT INTO student(rollno,name,marks) VALUES({},'{}',{})".format(r,n,m)) mydb.commit() print(mycursor.rowcount,"RECRD INSERT HO GAYA")
18
Lecture15 # SELECT QUERY import mysql.connector conn=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="stu dent") c=conn.cursor() c.execute("select * from student") r=c.fetchone() while r is not None: print(r) r=c.fetchone()
19
Lecture15 #WHERE CLAUSE import mysql.connector conn=mysql.connector.connect(host="localhost",us er="root",passwd="12345",database="student") if conn.is_connected==False: print("Error connecting to MYSQL DATABASE") c=conn.cursor() c.execute("select * from student where marks>90") r=c.fetchall() count=c.rowcount print("total no of rows:",count) for row in r: print(row)
20
Lecture15 #INSERT MULTIPLE RECORDS import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",pas swd="12345",database="student") if mydb.is_connected()==True: print("connection ok") else: print("error connecting to mysql database") mycursor=mydb.cursor() n=int(input("enter how many records u want to enter")) for i in range(n): r=int(input("enter the rollno")) na=input("enter name") m=int(input("enter marks")) mycursor.execute("INSERT INTO student(rollno,name,marks) VALUES({},'{}',{})".format(r,na,m)) mydb.commit() print(n,"RECRD INSERT HO GAYA")
21
Lecture15 # UPDATE COMMAND import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student ") mycursor=mydb.cursor() mycursor.execute("UPDATE STUDENT SET MARKS=100 WHERE MARKS=40") mydb.commit() print(mycursor.rowcount,"RECRD UPDATE HO GAYA")
22
# DELETE COMMAND import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",pas swd="12345",database="student") mycursor=mydb.cursor() mycursor.execute("DELETE FROM STUDENT WHERE MARKS<50") mydb.commit() print(mycursor.rowcount,"RECRD DELETE HO GAYA")
23
# DROP COMMAND import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="stud ent") mycursor=mydb.cursor() mycursor.execute("DROP TABLE STUDENT")
24
# ALTER COMMAND import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",pas swd="12345",database="student") mycursor=mydb.cursor() mycursor.execute("ALTER TABLE STUDENT ADD GRADE CHAR(3)")
25
#SEARCH AND DISPLAY import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",d atabase="student") if mydb.is_connected()==True: print("connection ok") else: print("error connecting to mysql database") mycursor=mydb.cursor() mycursor.execute("SELECT * FROM STUDENT") rs=mycursor.fetchall() n=input("enter name to search") for row in rs: if row[1]==n: print(row)
26
Lecture15 #menu driven project using database connectivity print("INSERVICE COURSE 2019-20 BHOPAL") import mysql.connector import sys while True: print("MENU") print("1-create database\n2-show database\n3-create table\n4-show tables") print("5-DESC TABLE\n6-insert into table\n7-select query\n8-where clause") print("9-INSERT DYNAMICALLY\n10-update\n11-delete\n12-exit\n") ch=int(input("enter your choice")) if ch==1: mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345") mycursor=mydb.cursor() mycursor.execute("CREATE DATABASE SCHOOL") if ch==2: mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345") mycursor=mydb.cursor() mycursor.execute("SHOW DATABASE") for x in mycursor: print (x) if ch==3: mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student") mycursor=mydb.cursor() mycursor.execute("CREATE TABLE FEES (ROLLNO INTEGER(3),NAME VARCHAR(20),AMOUNT INTEGER(10));") if ch==4: mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student") mycursor=mydb.cursor() mycursor.execute("SHOW TABLES") for x in mycursor: print(x) if ch==5: mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student") mycursor=mydb.cursor() mycursor.execute("DESC STUDENT") for x in mycursor: print(x) if ch==6: mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student") mycursor=mydb.cursor() sql="INSERT INTO student(rollno,name,marks) VALUES(%s,%s,%s)" val=(3,"RANJITA",99) mycursor.execute("INSERT INTO student(rollno,name,marks) VALUES(%s,’%s’,%s"%val) mydb.commit print(mycursor.rowcount,"RECRD INSERT HO GAYA") if ch==7: conn=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student") c=conn.cursor() c.execute("select * from student") r=c.fetchone() while r is not None: print(r) r=c.fetchone() if ch==8: conn=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student") if conn.is_connected==False: print("Error connecting to MYSQL DATABASE") c=conn.cursor() c.execute("select * from student where marks>90") r=c.fetchall() count=c.rowcount print("total no of rows:",count) for row in r: print(row) if ch==9: mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student") mycursor=mydb.cursor() r=int(input("enter the rollno")) n=input("enter name") m=int(input("enter marks")) mycursor.execute("INSERT INTO student(rollno,name,marks) VALUES({},'{}',{})".format(r,n,m)) mydb.commit() print(mycursor.rowcount,"RECRD INSERT HO GAYA") if ch==10: mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student") mycursor=mydb.cursor() mycursor.execute("UPDATE STUDENT SET MARKS=100 WHERE MARKS=40") mydb.commit() print(mycursor.rowcount,"RECRD UPDATE HO GAYA") if ch==11: mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student") mycursor=mydb.cursor() mycursor.execute("DELETE FROM STUDENT WHERE MARKS<50") mydb.commit() print(mycursor.rowcount,"RECRD DELETE HO GAYA") if ch==12: sys.exit()
27
THANK YOU
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.