You are on page 1of 29
Interface Python with SQL g.1 INTRODUCTION patabases play a vital role in the efficient working of an organization. From a construction firm to astock exchange, every organization depends on large databases. These are essentially collections oftables and are connected with each other through fields or, more precisely, columns/attributes. ‘These database systems support SQL (Structured Query Language), which is used to access data and also to create and exploit the relationship between stored data. Additionally, these databases support database normalization rules for avoiding redundancy of data. Python programming language has powerful features for database programming. Python supports various databases like MySQL, Oracle, Sybase, PostgreSQL, etc. It also supports Data Definition Language (DDL), Data Manipulation Language (DML) and Data Query Statements. But Python standard library does not come with an RDBMS interface. For database programming, the Python DB-API is a ‘widely-used module that provides a Database Application Programming Interface. It is 2 standard for database interfaces. Database Application Programming Interface is a set of tools, used by an Application program to communicate with the Operating System or other programs such as Database Management System. These APIs are implemented by calling functions in the programs which provide linkage to the required program to perform a task. Most Python database interfaces adhere to this standard. We can choose the right database for our application. Python Database API supports a wide range of database servers such as— * GadFly + mSQL + MysQL * PostgreSQL * Microsoft SQL Server 2000 * Informix * Interbase * Oracle Sybase 8.2 PYTHON-MySQL CONNECTIVITY While designing reali ications, certain situations Re eer aon important and necessary information by the user, Usually, the data TPN nae with the generated output is displayed but not stored beca all ee te hie! FOF ES sain : inside the RAM which is a temporary memory and as soon as We © aa pat mae pier {Form input and generated output) get erased. They can't be retriewwll UNA A At Rad ona hard disk (or any secondary storage device). Thus, when the appli he Berean pap ae time, it requires a new set of inputs from the user. This limitation can f° ONE TNT Osh the output generated and saving the input fetched from the user In a ae back-end of the application. The input is fetched from the user using PY! + This is termed as the Front End Interface of the application. arise pertaining to storing some Fig. 8.1: Front-end (Python) and Back-end (MySQL) Database (The Back-End) While working with an application, it is required to save data permanently on some secondary storage device, which is usually the hard disk, so that stored data could be used for future reference, modification, deletion and retrieval. An application usually stores a lot of data in the form of a database which is not directly accessible to the user. This database is used by the application to give suitable response to the user. This database is called Back-End Database. In Chapter 8, we learnt how to create databases, tables and how to perform query processing on these tables using SQL commands like CREATE, UPDATE, ALTER, INSERT, DELETE, SELECT and so on in various forms according to their specific syntax structures. We shall be implementing all these DDL and DML commands of SQL through Python Interface, 8.3 WHY PYTHON Python isa flexible, portable, easy to learn and modifiable language. So, with Python interface for executing any database applications, The vari for programming database applications are: we are integrating MySQL Python Us reasons to * Programming in Python is arguably more efficient and faster as compared to other languages + Python is known for its portability, + Itis platform-independent, a «python supports SQL cursors, In many Programming languages, the application developer needs to take care of the open and closed connections of the database to avoid further exceptions and errors. In Python, these connections are taken care of, Python supports relational database systems, + Python database APIs are compatible with various databases, so itis very easy to migrate and port database application interfaces, 8.4 INSTALLING MySQL-CONNECTOR to establish connectivity between Python and MySQL, we require Python Database Interfaces and APIs. We must download a separate DB-API module for each database we need to nccose The DB-AP! Provides a minimal standard for working with databases using Python structures and syntax wherever possible. This API includes the following: + Importing the API module + Acquiring a connection with the database + Issuing SQL statements and stored procedures + Closing the connection Our ultimate goal is to connect Python with MySQL. To do this, we need to install a connector. Steps to install the connector and connect it to Python are explained below: Step 1: To connect Python to MySQL, we have to install mysql-connector using ‘pip’ command on the command prompt (cmd). Command Prompt EET coon U eae eee oases a Noten et ere re\preeti\AppData\Local>ed Prograns -A\appData\Local\Pro: 4NippData\Local\Prograns\Puthon3ed\ Pytlion 32-32 iieastr iran cus tec Wsers\preet i\AppData\Local\Prograns\Puthon ed Python3: #\sers\preet i\AppData\Local\ installed in the same folder as Python and takes the Users\your name\AppData \Local \Programs\Python\Python37- Scripts> a 4 Step 2: Once you have set the path, type the command as— python -m pip install mysql-connector or stall mysql-connector-python ‘Command Prompt SER srs CEN EY TTS :\Users\preeti\appData\Local\Prograns>cd Python \Users\preeti\appData\Local\Prograns\Python2ed Python 37-32 ae ieec era serena escets ce \Users\preet i\appData\Local\Prograns\Python>ed Python3?-32 RT NNN NPN PERT NEN ENN Cp ea Rerpuetaa es Babee s tr i rete Pres fe es re Stes es ROR ZA aCe AP CRE are ETRE RT ett Tat tr AMPS tS at pe GO recararrrer een RYE ey Deca eS re mses pSoREe ear Saree tm Cres eens as Enters ea ste eed pears Rea ess reeset ie a Sate Cn Oe ce a on should consider upgrading via the *python —m pip all —-upgrade pip’ conn) = \Users\preeti\fppData\Local\Prograns\Python\Python37_32\Scvipts> Mysql-connector shall download and will be installed on your system. Now we need to check whether it has been properly installed or not. Step 3: To do this, type import mysql-connector in Python shell. If no error message gets displayed, this signifies that driver bas been successfully installed. SSS WySql. Connector | >>> | Ina nutshell, three things are to be kept in mind for the successful installation of mysql connector: > Ensure that Python has been already installed onto your system. In case there is no Python installed prior to connectivity, download Python 3.x and then install it > Download MySQL API, exe file will be downloaded; Si nstall > Install MySQL-Python Connector > Now connect MySQL Server using Python. (CT: MySQL Connector Python requires Python to be in the system's PATH. Installation fails if it doesn" find Python. Alternatively, We can also establish the connectivity through the module “MySQLab” Let us first discuss the basic concepts related to MySQLdb, 8.4.1 MySOLdb MySQLdb is an interface for connecting to a MySQL database server from Python. Itimplements the Python Database API and is built on top of the MySQL C APL. GR 4 1% 8.2: Components of MySQLdb What is Mysaudb? Python-MySQL Database Access MySQLdb is the Python interface to work with MySQL. databases. It must be imported in Python to vwork with any MySQL. database. To import MySQL for Python 3.x, first, the module MySQLelient needs to be installed as follows (assuming Python is already installed with pip and ite path included for Windows 8 or 10): > Open 2 command window (cmd). > Type the following at the command prom| tall mysqiclient ‘After mysqlclient is installed on your system, MySQLdb needs to be imported as shown below: + Open Python shell at the command prompt: : C:\>Python + Import MySQLdb in Python shell >>> import MySQLdb ' the above command produces the following result, it means MySQLdb module is not installed, bes unos Fees cence aes ieee) ireaeccen laser IS aR shoe det atte aed Ph mysql module for the Python version you are using is not stalled, it can be downloaded from: ““P://sourceforge.net/projects/mysqlpython ~ This is followed by and creating objects for interacting with MySQL connector installation, which we have discussed establishing connection Python, Therefore, mysql- recommended in the previous section (8.4) is for use, actually implementing SQL commands ning at the re not aware of, One more thing to be taken into account is that befor through Python interface, we can check for the mysql client p back-end of the program. To check for MySQL user, about which s the following command can be executed on MySQl. prompt mysql>SELECT o ser () urrent_ i 7 ySQL client program, This command shall display the username which is running on MySQL client prog [EE eaProgram Files (a6 MySCAMySAL Sever 5.1\bin\mysalexe Saas nes peeeriee SONS CE Rae CaS e SRN CRS 8.5 ESTABLISHING CONNECTION After completing the first step of installing mysql-connector, the next step to using MySQL in Python scripts is to make a connection to the database that you wish to use. All Python DB-API modules implement a function: ‘module_name.connect’ This is an essential function required to connect to the database, which is MySQL in our case. Note: Ensure that the username and password you are entering for MySQL should be correct. We have used “root” as username and blank (“") as password for all implementations connectivity. Practical Implementation-1 To establish a connection between MySQLdb and Python: Create the first program in Python script mode for establishing this connection, Open a neW script file in Python, type the following script and run © mysql -connector yd = aysql .connector.connect (hos! [prine cayab) Ifthe output as shown below is obtained, thi Signifies that the connection has been successfully established. RESTART: €:/U0ers /pre0tl/Appoata/tocal/?rogeonay [prog pysan_pythi-py 2 Fenyanh -conector.ednnection.nysou Python /eytvona7-22/ Weonnection ebjact at axo2ans470» We will now understand the above commands in detail, ‘The first statement is to imp: on your system. The next statement involves the cresti he connect() method creates a connection to the MySQl server and retumea MySQL Connection object. Thus, the following steps are to be followed while connectin, + Open Python. * Import the package required (import mysql.connector). + Open connection to database. * Create a cursor instance. ig your Python program with MySQL: * Execute the query and store it in ResultSet. + Extract data from ResultSet, * Clean up the environment. 8.6 CREATING CURSOR OBJECT The next step for interacting with MySQL through Python is to create a cursor object. It will let ‘s execute all the queries we need. Thus, in order to put our new connection to use, we need ‘create a cursor object. It is a useful control structure of database connectivity. When we fire any data manipulation query to database, it is executed and the result set (set of records) is sent ‘ver the connection in one go. Although we may want to access data one row at a time, query Processing cannot happen one row at a time, so cursor object helps us perform this task. The cursor object stores all the data as a temporary container of returned data and allows traversal ‘that we can fetch data one row at a time from cursor. i ‘he cursor object is an abstraction specified in the Python DB-API Itgives us the ability to have "ultiple separate working environments through the same connection to the database. e eed to create the object of a class called cursor that allows Python code to execute database mmands in a database session. i naa tt taetteecien * Cursors are created by the connection.cursor() method: they are ar ciaitabaunssicion ‘he entire lifetime and all the commands are executed in the conte Le “rapped by the connection. “~ alll We can create a cursor object by executing the cursor() function on our database object. Establishing the connection with MySQL. database requires the following steps to be executed (Fig. 8.3): Use mysql.connector.connect() method such as host name, username, password 2. Use the connection object returned by a connect() method to createa cu database operations. Use/type the cursorexecute() to execute SQL queries Close the Cursor object using a cursor.close() and MySQ connection.close() after your work gets completed. of MySQL.Connector Python with required parameters and name of the database to connect to MySQL, from Python. . database connection using 5. Catch Exception if any that may occur during this process. Python DB API Python DB API v2.0 (PEP 249) 11 mysqliconnectorconnect() plea connec one MysQl Connector Python Python [4 _connection.cursord) eee Application 5 Cursorexecute(query) rE———— Fig. 8.3: Python-MySQL Database Connection Arguments required for connecting MySQL database with Python: > Username: This is the username that you use to work with MySQL Server. The default username for the MySQL database is “root” > Password: Password is given by the user at the time of installing the mysql database. If you are using root then you won't need the password. > Host Name: This is server name or IP address on which MySQL is running. Ifyou are running on localhost, then you can use localhost, or its IP, ie., 127.0.0.0 > Database Name: It is the name of the database to which connectivity is to be established. Here we are using a Database named ‘school’ which we will be creating in the upcoming section. 8.7 CREATING A DATABASE Once the connection gets established, our next step is to create the new database ‘school’ in MySQL through Python. Before creating this database, it is advisable to check whether this database already exists or not. This is done by typing the command— SHOW DATABASES; in the front of MySQL prompt (mysql>). sor object to perform Te Je \Program Files 0) MySOL\NySOL Sen) 4s is evident from the above screenshot, no database named ‘school’ exists, So, we will now ‘reate a database named ‘schoo!’ practical Implementation-2 qo create a new database ‘school’ in MySQL through Python: this is done by typing the command “CREATE DATABASE " after establishing the connection and creation of cursor object. In our example, it will be: “CREATE DATABASE school” in new file created using Python script mode. {pros alt= Csr preeti/AppOsta/Local/Progiams/fyihowPythoeaT 2) preg sabyti py) Lae ‘#70 create a new database ‘school’ from python to mysql | import mysql connector mya = mysql -connector.connect (hos nycursor = mydb.ci nycursor execute ( localhost, user="zoot™, passwd=") | On successful creation of this database, if no error is displayed and the cursor starts blinking in front of the Python shell, this signifies that database has been successfully created. Wecan further check the creation of database ‘school’ by typing SHOW DATABASES; command in MySQL prompt. The screenshot given below shows that database ‘school’ exists. Pert eRe Bree Porc cant iran Pans RESTART: C:/Users/preeti /AppData/Local/Prograns/Pyth on/Python37-32/prog_salpythl.py re [a Understanding the Python MySQL Database Connection Program © import mysql. connector + This line imports the MySQL Connector Python module in your program so you can use this module's API to connect MySQL. r shall be displayed— In case the connection fails, import e from mysql.connector import Error + mysql-connector Error object is used to show us an error when we fail to connect databases or if any other database error occurs while working with the database, Example: ER_ACCESS_DENIED_ERROR when username or password is wrong, © mysql.connector. connect () + Using this function, we can connect the MySQL Database; this function accepts four required parameters: Host, Database, User and Password that we have already discussed. = connect () * connect() function establishes a connection to the MySQL database from Python application and returns a MySQLConnection object. Then we can use MySQLConnection object to perform various operations on the MySQL Database. * connect() function can throw an exception, ie., Database error, if one of the required parameters is wrong, For example, if you provide a database name that is not present in MySQL, then Python application throws an exception, So, check the arguments that you are passing to this function. © conn.is_connected() + isconnected() is the function of the MySQLConnection class through which we can verify if our Python application is connected to MySQL. This function returns True if connection is established, otherwise returns False. © connection. cursor() + This method returns a cursor object. Using a cursor object, we can execute SQL queries. + The MySQLCursor class instantiates objects that can execute operations such as SQL statements. Cursor objects interact with the MySQL server using a MySQLConnection object. @ cursor().execute() Usually, a cursor in SQL and databases is a control structure to traverse over the records in a database. So it is used for fetching the results. We get the cursor object by calling the cursor() method of connection. An arbitrary number of cursors can be created. The cursor is used to traverse the records from the result set, Note: The execute() method accepts arguments of SQL statements in String format, ie, enclosed in double quotes. Argument can be used in any one of the forms: use SQL statements in triple quotes (”") along with semicolon (;) or use SQL. statements without semicolon (i) In the above program, cursor object, which is ‘mycursor, is used to execute Create Database command using Python shell. Moreover, we have verified the creation of the database from SQL: Cameco eke ole sis can be done from Python also as discussed in Practical Implementation-3, practical Implementation-3 ‘to check whether the database has been created or not using Python interface, import mysql.connector nya = nysql.connector.connect (host="localhost,user™*root™,passude"*) Inycursor = mydb.cursor () Inycursor.execute "stow DATABASES") for x in nycursor: print (x) Upon execution of the above code, the output window shall display all the databases present in MySQL in the front of Python shell. :/Usexs/preeti /appbata/Local/Pr Jograns/eython/Python37~32/prog_aysqlpytn2. PY (‘information_schena',) (nye) (school) (test!,) (test_do',) Inthe above program, for loop has been used to traverse among all the databases present inside MySQL using the cursor object ‘mycursor’. TM: We can execute the SQL queries from Python program using execute() method associated with cursor object. Once we are done with the creation of ‘school’ database in MySQL, our next step is to create a lable inside this database through Python shell. Practical Implementation-4 Tocreate a table ‘student’ inside the database ‘school using Python script mode as the interface. ¥fo cxeate a table in uysgl using Python Interface import mysql «connector yj | ean Tun the given script in Python file using CREATE TABLE command of Python, If no error is displayed, this means the table has been successfully created and os verified by using desc command, ie., desc student; in MySQL promp! ich shall display the structure of the table student in MySQL. Sry ener eas Hae ce Roead Lemoine eet) rey This can also be done directly from Python shell by typing the script given in Practical Implementation-5, Practical Implementation-S To check for the created table ‘student’ using Python. [pon sald py soe peni/appostftoc/Ponrens/tyhon a) => Raa ‘MySQL using Python Interface import mysql .connector Inyab = mysql -connector.connect (host="1ocalhost",\ Inycursor = mydb.cursor () Inycursor-executs ("sHo# TABLES") for x in mycurso: print (x) In the above program, SHOW TABLES command in SQL is executed using the cursor object ‘mycursor’ in Python script. This shall display all the tables present inside the database school by using for loop for traversing all the tables present inside it and, hence, the output is obtained as shown below. RESTART: C: /Users/preeti /Appbata/tocal/? rograms/Python/Python37-32/prog. sqlpyehs, Py (student, ) Similarly, we can implement any DDL (Data Definition Language) commands in MySQL usin Python. Implementing DDL Commands using Python Shell We will be discussing an important DDL command in s ies QL to modify the structure of the already created table ‘student’ using ALTER TABLE comma Y ind in Python script. practical Implementation-6 add a new column ‘marks’ in the student table, 0 Opens Wadow “Hep ‘#70 Rodify table student (addi #MySQL using Python Interface import mysql. connector frrdb ~ mysql .connector.connect thost="1ocainost",\ user="root", \ asswde"", \ database="schooi") mycursor = mydb.cursor() pvcirsorvereevte("Alter table student add (narks int (3))*) implementation-7. Practical Implementation-7 Toview the modified structure of student table using Python script. iedified structure of table student ia }#4ySQU using Python Interface import mysqi .connector /pyd> = mysqi.connector connect (host="iccalhost*,\ user=root", \ asswa="", atabase="Scnoo1" fnycursor = aya .cursor() Rycursor.execute(*Desc student) for x in mycursor: print (2) Upon the execution of the above script, the following output shall be displayed as shown in the Screenshot given below. RESTART: C:/Users/preeti /appDat/iocal /Prograns/ Python/Bython37~32/prog_mysqipyth3.py CRolino', Vint (3)", "8 (mame', “varchar (5)", Hint", "YES", TEs "Mone, 1) >>. stow in the output displayed, the structure of the table gets displayed in the form of tuple strings, ie nxt Step is to populate this table, ie, insert a record into the table student using : SERTINTO command through Python Interface. Ns “"ting Records into Student Table the table student has been successfully created and altered, we will add records : it sing Popular SQL-DML. (Data Manipulation Language) command INSERT INTO using Python shell. Practical Implementation-8 ‘To insert a record into the table student u: 1g Python Interface. 'sQl using Python Interface mport aysql connector nya ~ nysql .connactor.connect (host="localhost*,\, passwd", Gatadase=*school") N Inycursor = nydo.cursor() 4 Jaycutsor.execute("INSER? rr0 student VALUES (2, "Tarun", 23, ‘Munb faya>.comit 0) tt ay aitianta eatery “Este foment eee ace I + The cursor.rowcount is the property of cursor object that is used in the given program and shall return the number of records inserted which is 1 in our case since we have inserted only one record into the student table. * For storing String data type values, all the string values should be enclosed in single quotes. We can insert multiple records also at the same instance through Python, Practical Implementation-9 To insert multiple records into the table student through Python interface. ‘MySOL using Python Interface f sport mysql.connector } nya = nysq) -connector .connect (host="1oca! | databaze="scho01") cua =m. ccrty Peers 1380)" ‘Shinda' , 308)") Goa", 300)5) ‘Pune! 430) 125, "Deis", 345) ") Bh ometoy -CrveneRgpDanocalmegamryeniten ieee pyO9n¢ tie (a forma an Ops Wow ep igure mysal.comector inpdbrnysgh-comectorconnect fhst="1oca inyeursorenj.cur20r() Inycursor-exeeate("*"Insce tno at ae Eee re Inthe above code, we have used a function commit() which we will discuss now. (nim) However, we must remember one thing: after executing insert or update query, we must commit our query using connection object with commit(). For example , (if our connection object name is mycon) mycon.commit () This statement is required to make changes in database permanently; otherwise, no changes are made to the table, Methods to Manage MySQL Database Transactions in Python Python MySQL-Connector provides the following methods to manage database transactions (Fig. 8.4) * commit: MySQLConnection.commit() method sends a COMMIT statement to the MySQL server, committing the current transaction. * rollback: MySQLConnection.rollback() reverts the changes made by the current transaction. * autocommit: MySQLConnection.autocommit value can be assigned as True or False to enable or disable the auto-commit feature of MySQL. By default, its value is False. All Queries executeda successfully Transaction (Query 1, Query 2 initiate transaction Any of the ‘Queries failed Query nt Transaction failed 5 7 Fig, 8.4: Python-MySQL transaction management using commit > Syntax of commit() method and you wal Once a program has completed executing the query with your ch: want to commit the changes to the database, then you need to call commit() method on MySQI. connection object as follows: connection. commit () > Syntax of rollback() method When one of the transactions fails to execute and you want to revert or undo all your changes, then you need to call a rollback method of MySQI. connection object as follow: connection. rollback () ‘That was all about transaction handling using Python-SQL connectivity. In Practical Implementation-8, after multiple records have been inserted into the table student, it is checked using SELECT statement in SQL. This can be accomplished in Python as well. Practical Implementation-10 To display all the records of student table using Python shell. Tie 6 Tom fon_Opm_Windn_Hep jftxeciting SELECT statement using Python ae Imycursoz = myd>-cursor() fmycursor execute ("Select * from student) Imyrecords = mycursor.fetchall( for x in myrecords: peint +: c:\Users\preots \Appbata\Local \Program, /s\pythion\rython37~32\prog mysqlpythe.py (Q, Mtarun!, 23, ‘mumbai, 398) (2, *Pooja", 21, *chaia','390) G3, *Radhika", 48, "shimia*, 200) ||, ssonia', 24, toa", 300) (5) "Vinay", 25; "Pune, 410) (26, *shaurya’,"15, ‘Delni", 345) In the above program, we have used SELECT statement along with fetchall() function. This function is used to read and display all the records as tuples from the table student. READ Operation READ Operation on any database means to fetch some useful information from the database. + Once our database connection is established, we are ready to make a query into this database. We can either use fetchone() method to fetch a single record or fetchall() method to fetch multiple values from a database table, + fetchone(): It fetches one row from the result set in the form of a tuple or a list. A result set is an object that is returned when a cursor object is used to query a table. This function shall return one record from the result set, ie., first time it will return the first record, next time it will return the second record and so on. If no more record is left in the table, it will return None. a wS + fetehall() I fetches al the rows ina result sot andl returns alist of ples, {some rows have already been extracted from the result set, then it retrieves the remaining rows from the result set. If no more rows are available, it returns an empty list. + fetchmany(size): It fetches the specified number of rows (asa list of tuples) from the result set, The default size is 1; if there are no rows in result set, an empty list() is returned), In other words, it will return an empty list p roee Niet ies * Fal 960? S@rlits Sed vet ys the ansciser of es thet were affecans by an execute() method and retrieved from the cursor. er ale ey ed gi ad the abject myrecords’ which we can display one by one using for loop, Practical Implementation-11 (Modification of Practical Implementation-10) Todisplay all the records along with the total number of records from student table using Python shell, [nes mvaotiy- CunensanapbsaaaNGSamINC STS fie Wt tent Re he vine fae — laplaying total no. of records slong with ——-| fall the records of the table | sport mysql -comector sydd = nysql.comector connect (host="ZocsInost,\ passwd, Satabase="Sehoot") barr © ayaicirsnt) encores" apentotfoton iG | rrecipear serra petse Teel noo eek coun a | or an neces fine { " 1 RESTARTS ct\Usere\preoti(Rppoata\tocal\rogeans\Pytton\Fython9?-22\pr09_syealpy Fee, ot rr ta ae | ; ‘foen',"sM', Decimal (*83.00"), stating, date2008," 95°11), sgaeas :(150.00¢D, Mone, "Delni!) This program is a modification of the previous implementation. It displays the total number of records retrieved from the table ‘student’ apart from all the records being displayed. The umber of records fetched is displayed using the attribute of the cursor object, ie,, rowcount. This attribute counts the number of records retrieved from the table and the output shows the ‘otal number of records as 4, which are also displayed alongside. Asis evident from the output screenshot, the records are displayed one by one as a tuple. We an display the records row-wise as well instead of a tuple. "do so, we have to slightly modify the for loop control variable as shown unde Displaying recorse indivichally Wh ¥ FOV natesd of tuple sport mysql comnectoe ub = eyagl connector connect ost Schall no recmnpcoreds.foncoune oo print crsesl nes et goede ne. For enoy na geny asks dost in mjrecarde Another representation of the records using separator (:) in between the data being displayeg as records is shown below: Tor row in myrecords outa), 1", rOW{S], eee venee ota. of secoras sound i Eg S200", abeao9-12 «pein Siar a aah 1 ie Delhi 2 5 Practical Implementation-12 To display records from student table, one at a time (using fetchone()). Till the last implementation, we fetched and displayed all the records from the student table. In this implementation, we will be using fetchone() method to fetch and display the records from the table one by one or one at a time. Pe fy « ys comector comectnosto"Iccslhost*jusare*ecot" pasate" da yeersor = nycb-corsori). {Total no. of records found aror 2 2, ‘efdini', TP", Deciaal ("73.00"), datetine. cate 2002, $, 22), ‘Munbat) Practical Implementation-13 To display ‘n’ number of records from student table (using fetchmany(n)), This program shall fetch and display ‘n’ number of records from the table through fetchmany(n) method by passing the number of records to be retrieved as ‘n’. aDisplaying "a" no. of records wslng TLAMaRY OT ‘ysqi. connector ydo = apodi connector connect (hoste"Loca host" ‘pjab.cursor() fecute(vselest * fron student”) 2) fy Beeinal(*€3.00"), aacer okelaan pea Toecinad 23t0(2009, 5, 12), “pein 20), sete. caie 000, 3) 2) gabe) astetine cate zoot, 9,13), sseineth In the above program, three has been passed as an argument to fetchmany() method and, hence the output displayed shows first three records from the student table. a~ clause ing WHERE Selection u We can retrieve selected records from the table using WHERE claus manner as is done in MySQL. In Python shell also in the same al Implementation-14 Pract To implement WHERE clause using Python interface, ‘This is to be implemented using MySQL. Select..Where statement in Python script as shown in the given code: 2 prog salpythuwteretby «CiUser/p ae {8% Fora Ron Option Window Hey Himplenenting SELECT statenent Using #WMERE clause in Python Interface f import mysql.connector | J tvs * n¥sai-connector. connect (host="ocathost,\ user="root", \ Passwd=' database choot") [Jnycursor = mydb.cursor() i Jmicursor-execute ("select nane,age,marks trom student where city="Deihi nyrecords = mycursor.fetchall () |] for x in myrecords: ] print (x) In the WHERE clause, we have used city='Delhi, ie, to fetch the records ofall the students who are staying in ‘Delhi city. Since there is only one record in the table that matches with the given criteria on, it shall be displayed as shown: 3 ee €:/oee/prett epost wherel.py (shaurya’, 15, 345) >>>. Parameterized Queries Apart from entering the values statically in the program to search and display the records from Stable, we can pass values to query to perform dynamic search, for example, to search for any Student roll number entered during run-time or to search for any other column values, etc, To create a Parameterized query, any of the following methods can be used: 1} Concatenating dynamic variable to query in which the values are entered ) iG} cy String template with %s formatting String template with {} and format function Concatenating dynamic variable to a query : i i In this method, a dynamic variable is created that fetches the input for the field —— ‘© the query on the basis of which records are searched and displayed at run-time. Practical Implementation-15 fscaren a record at run-tinw By concatenating Yar [[Ssportnpsat connector oie | nyse = tysat‘comector.comect nostertocolhost“/ se I[micussor = njabvcussordr hosine (input inter tne roll number to seareh:") juery-"seiece » tyom stuent vhwre foll_pon"#ste (en0) rycursor-exeevte query) fnyeecord = mycursorsfetenone() Mayrecord = none? Print nyzecora) otse? SS prine (*uo such Tapio wit v=" oot" passudw"™ database="school") cu usere/peeeti/appbata/0eal/Pxogr883/@y%hon/ yeh rantinequery BY ae the soll misber te seazch:? ater eee rottpre peeimel 50-00"), None, ‘Dethi*) Presta ./osers/preeti /Appbata/Local/Programs/Python/ fh puntineguery-bY Eptat tne Fell fiber to seazchs10 (b) String template with %s Formatting In this method, %s is used in place of values to be passed that define the search criteria on the basis of which records are retrieved at run-time. | ssa tinea Crea ce poser sal nop na RoaT S/peamyalnyaunonegay = AES [Ff tae ft ton open inate #Search a record using String tanplate with ts formatting @ Snport mysql connector nya = mysql :connector .connect (host="1ocalhost",user="root",passud="", database="'school") Inycursor = mya cursor) Movint input (Enter ehe roll number to searen:*)) Jauery="soiect = fron student vere foll_newts"4 (eno, ) Rycutsor.execute (query) Inyrecord = nycursor. fetchone () Bf myzecord t= son Brine (ayrecord) Jerse eine ("to such student found") sg 1 RESTART: C:/Users/preeti/appData/Local /Prograns /Python/Python37-32/prog. mys yen runtinequezy.py: Pog. }/Python/Python37-32/prog_mys ‘a Entér the roll number to search:2 (2 teiddhi'y *Ft, Decinal('73.00"), datetine.date(2002, 5, 22), ‘munbai') = Using multiple conditions [SOT aT TRS Saas [Fevarch a record on mutiple Conditions wsing Ging Template WIG Tors z ser ete cometee estes Formatting Fi ‘= jog! connector connect (host="Localnost user=root, pasayde eee fRyctesor = njab.corsor 0) ‘passwd eatabasenschoot") || fRee~ine (Amput ("enter marks to be, seazch:")) tsinput "Enter state to seazch:*) Jqveryessclect + fron student whet state="43" and ma juror execute quesy) Syrecors = nycursor-fetehall() no, recenyoursor.rowcount prTae (Total records matching the extteria a Pn croe EINE (nyrecord) ko >8S°8 (st mek) no_tec) print RESTART: C:/Users/preeti/AppData/Local/Pr |_pyen runeSmequery py Enter marks to be search:60 inter state eo search:Delnt otal records matching she criteria are: 2 1), taiddhazth', "My Deeinal (*03.00"), datet ine, (al stearate tn pecimal(*63.00"), datetinesdace aang oot? a ‘ograms/Python/Pyttion37~32/prog_ mysql 32), Deans"), ae 8, ia), tDelnity} F © (o)_ String template with () and format function In this method, In place of %s we use () placeholder and using format() fanetion, As an argument, we can ph Bument, we can give {o}41) for valuel and value2 respectively, five 0,1,2 values to this placeholder by + values but it is optional, eg,, vt mysql. connector Bu to's dad conector coaneck test sors mpabvenrserts fanrysce ect ftam sedan ape Sch" aeeyeorsexecute gueast Shon} format zn) Trecend = ayennser ieeshone i Spencora Tatceet ® Prine npeecors) print ("No such stud localhost", user="root™, passwd SS RESTART! C: /Users/preeti/ay 00% ’ | pyen runtinequery pyr tt/ BPPDAEa/Local /Prograns/Python/Bythond7-22/pr09,_ Enter roll nunber to be search:5 (Gr teen's H's Decimal ("83.00), datetine.date(2004, 9, 11), ‘pethi*) © Using multiple conditions [Siac CRS fi tt Femt fon Opes Wade ap ‘Search a record on mutiple conditions Welng Strlig tanplate vith T) nde ort mysql-connector 'g String template with (J and format () rao = mysql. connector connect host="iocaihost”,user="ract*passude",databe nyeursor = mydb.cursor () fmrkeint (input ("Enter marks to be searen:*)) Jsteinput ("Enter state to searchs") | jquery="select * fron student where states! (state)! and marks >=(narks)" sycursor execute (query) yrecord = mycursor.fetchall () no_recemycursor.rowcount print ("Total records matching the criteria are: *,no_rec) it no_gee !=02 PEint (nyrecord) ease Print ("o such student found! ATT OOS 'Schoo1") format (staterst,marks=mrk) | > RESTART: C+ /Users/preeti/AppData/Local /Prograns/Python/Python37-32/prog_ysq |_pyth_runtimequery.py Enter marks to be search:60 inter state to search:Delhi Total records matching the criteria are: (, ‘siddharth’, 'M", Decimal ("83.00"), datetine.date(2003, 9, 12); {te (5, '*teenu', 'M*, Decimal ('€3.00'), datetime-date(2004, 9 11), 9, 12), ‘Delhi'), hserting Records dynamically using () and Format Function ertion of the records statically. Insertion In Practi ins tical Implementation 8 and 9, we have done in: () method. "cords can be done dynamically, ie, at run-time as well using () and format() a —s aa a AAO UDR STS TRL ROE OIE ay {at fort fen pom Wind He ——— ffinsert records dynamically waing {) and format 0 Snport mysql connector Inyab = mysql. connector. connect (host mycursor = nydb.cursor () print ("student fecord Insertio choices "y" 7 juniie choice =="y* -:no=int (input ameinput gneinput ("enter mrks“int (input ( dbeinput ("Enter the dats of birt st=input ("enter state:") a no, tm, gies, uery*"insext into student values ({O}, "(2)", (2)"¢ (3), "{4) ty ‘(51 ') "-foxmat (eno, nm, gn, mirks, db, st) mycursor execute (query) nny. const () Print ("## Record (5) added... & choicesinput ("want to add ocathost™,users"root™,passude"™, database="school") enter the rolino:"}) ” NES records:") RESTART: C:/Users/preeti /mppData/Local| jyth_insertdynan.py [Student Record insertion | Enter the rollno:3 | Enter the nane:anisha | Enter gender: Enter the marks:88 Enter the date of birth:2000/09/12 Enter state:Mumbai 48 Record (s) added... ¢ lant to add more records:y Enter the rollno:4 Enter the nano:Geetu Enter gender:® Enter the marke:90 Enter the date of bizth:1999/02/13 enter state:Dehradun #8 Record (s) added... Want to add more records Deleting Records from a Table in Python-SQL DELETE operation is required when we want to delete some records from our table. Following is the procedure to delete all the records from the table student for roll number 1. Practical Implementation-16 Deleting records from the table student using Python interface, import mysql connector Jaya = mysql -connector .connect (host="1ocaihos' user="root",\ passwd database="Schoo1") IJmcuzsor = mrep cursor Imycursor.execute "DELETE FROM student where Roline = 1" mya. commit () eee [pEint (nycursor.rowcount, "Record (s) Deleted) be vr ‘This can be verified using the statement-SELECT * from student; in MySQL. Ren ean Sonia Vinay Pounce: iets) Asis evident from the above output, the record for roll number 1 has been deleted and, hence, not displayed. co RESTART: C: /Users/preet/appoata/] det py 1 T Record (s) peleted | Ss Updating Records in the Table using Python-SQL UPDATE Operation on any table means to update one or more records which are already available in the table. The following script updates all the records having Name as ‘Vinay’. Here, we increase AGE of students with name as “Vinay” to 28 years. Practical Implementation-17 To update the student record dynamically using string template with %s formatting, "prog salpyth Updt py - C/Users/User2/AppData/Local/Programs/Python/Python3M%/progs. — OX File_Edit Format Run Options Window Help Wpdating records through parameterized query in Python interface a ort mysql.connector nydb = mysql .connector.connect (host="1. nee (Age, Name) setae ee fycursor. execute (query, data) Bydb.commit () Print (nycursor.rowcount, "Record(s) Updated") v > RESTART: C:/Users/preeti/appbata >> ect an Pressey UC As shown in the output window above, the age of the student ‘Vinay’ has been updated from 25 to 28 years. Updating Records in the Table using Parameterized query In the previous example, we updated the student record statically by passing the values to be updated in the program itself. To fetch the values at run-time, ie, dynamically, we can use parameterized query through {} and format() method as given in the implementation that follows. Practical Implementation-18 ‘To update student record using parameterized query through {} and format(). jfupdating records dynamically by fetching input from user at run myc nysqi connector | mysql -connector.connect (host="1ocalhost",\ usere"rost",\ passwde"", \ database=*sehoo1") | Imycursor = mydb.cursor() Print ("student record Updation") Fnomint (input ("Enter rolino to query="select * from student YCUESOE execute (query) myzecord-nycursor. fetchone () if myrecord t= None: rint ("## Record Found- petals are: #4") Print (myrecord) choice=inpat ("Do you want to update maz date the record:")) 8 roll_no=()".format (rno) om) SP choice =="y"+ i mrks=int (input ("Enter new updated mark: d j query="UeDATE student set marks = {] whore roll_no-{)*.format tmeks,zn0 mycursor.execute (query) eee SFtmekss=n0) nysp.consit print ("## Record (s) Updated##") | is print ("sorry! No such student exists") nyd>.close() maniel PY student se¢ora Updation Enter rollno to update the record:4 ## Record Found Details are: #8 {yon Sunt’ to updeeg mah (190;00"), datetime.cate(1999, 2, 19), *Deheadun'y Do'you want’ to update marks: (y/n)y Enter new updated marks:60 48 Record (5) Updatedte Understanding Python MySQL Parameterized Query Program We used the function mysql -connector.connect () to connect the MySQL Database, This function accepts the required parameters: host, user, password and database. Ifa connection ig successfully established, it will return the connection object. + Firstly, we assign values to age and name variable which isto be inserted into the placeholders, + Then we create the parameterized Si QL query. In this query, we are using two placeholders “%s' for two columns in a table. + Next, we put two placeholders in update query, one for “name” column and the other for “age” column, contains user data in sequential order of placeholders. «Inthe end, we commit our changes to the database using connection.commit(). Practical Implementation-19 [ycursor = dbi.cursor() |Jaminput ("enter n: Rycursor execute ("DELETE FROM student WHERE Name = ‘nn')") Brint (mycursor.rowcount, "record (s) deleted”) el .comit () dbL.rollback() 1.close() \Users\preeti \appData\Local \Programs\Python\Python37 detesaipytn.py aaa TTESE Mame of the student whose record is to be deleted :Poo}: 1 record(s) deleted Explanation: We used the function mysql.connector.connect to connect the MySQL Database. This function accepts the required parameters: host, database, user and password, Ifa connection is successfully established, it will return the connection object. + Then we created the parameterized SQL query. In this query, we are using one placeholder, + Next, we used the prepared statement to accept user input using a placeholder, ie, we put one placeholder in delete statement for “name” column. + We then added this one column value in the input tuple in sequential order and passed sq delete query and input tuple with name as ‘nm’ to cursor.execute() function, + Inthe end, we commit our changes to the database using connection.commit() ‘+ We placed all our code in the try-except block to catch exceptions, if any. Practical Implementation-20 To delete the record of a student on the basis of name fetched from the user using {} and format() method. (3 prog deletion antinel Feat mi py = CJ Use prey App sa/LocalProgiame/bynon/Pyton37 22/pr09 dels = an Opto Weon Hi #@xecuting deletion at run tine using {) and format() method import mysql.connector /dbi = mysql .connector.connect (host="Localhost",\ mycursor = db1-cursor() nm=input ("Enter name of the student whose record is to be deleted #Preparing SQL statement to delete records as per given condition query ="delete from student WHERE nane='{)'". format (nm) mycursor .execute (query) print ("record deleted") db1. commit () dbi-close() poe RESTART: C: /Users/preeti /AppData/Local /Prograns/Python/Python37-32 n-runtinel.py Enter name of the student whose record is to be deleted :rinku 8.8 CLOSING CURSOR AND CONNECTION Since the database can keep open only a limited number of connections at a time, we must close the connection using cursorobject.close(). For example, cursor.close() or mycursor.close() ‘This method closes the cursor using cursor object which resets all results and we cannot execute any SQL statement. We can disconnect from the database after perfor method along with database object. For example, conn.close() all operations by explicitly calling close) a 8.9 OPERATIONS ON A TABLE IN A NUTSHELL Following is the program for performing all the operations on a table ‘student’ through ar driven program. henmpeer/ OTT c ep isonucariven progran to denonstrate four wajor operations J;petformed on a table through MysgL-Python connectivity Jaer mena()t err while (e==ty") + print ("1. add record") Print ("2. update record ") Print ("3. delete record” print ("4. display records") i print ("5. exiting") choicesint (input ("Enter your choice: “)) Af choice == 1: ‘adddata () elif choice== 2: updatedata () elie cholce== 32 deldata() elif choice== 4: fetehda elif choi print ( Break ) els ‘print ("wrong input") Je-input ("bo you vant to continue or not: * leet fetchdata ( inport mysql.connector ryt > = mysql .connector.connect (host~"localhost™, user="root", passwords" * database's") cursor = db.cursor() cursor.execute("SELECT = FROM student” ) results = cursor.fetchall () for x in results: print (x) except: print ("Error: unable to fetch data”) Jdot adadata) + inport mysql connector db = mysqi .connector. connect (host: cursor = db.cursor() Cursor.execute ("INSERT INTO student VALUES (*Ritu', 4000, "Science", 345, "BY, "11" cursor-execute cursor-execute: cursor-execute ("INSERT db. commit () print ("Records added") "* database= localhost! ,user=" root ' ,passwor ) INSERT INTO student VALUES (‘Ankush' , 6000, *Comnce", 445, A", "12")") INSERT INTO student VALUES (*Pihu' , 3566, "Humanis', 446, A", "11")") k INTO student VALUES (*Tinku! 8900, 'Science",545, 1a", 1121)" Jeet updatedata() import mysql.connector try: sit) > = nysqi.connector.connect (host="Localhost™ user=root", passwords" ' databast cursor = db.cursor() sql ("update student set stipend-5000 where name='Ritu'™) cursor.execute (sql) print ("Record Updated") E @.commit() } except Exception as e: Print (e) Jeet dendatay): import mysql -connector 92" = nysql..connector. connect (host="1ocalhost™,user="root", password="', database="s1") cursor = db-cursor () sal = "éelete trom student where nane="Ritu’ cursor execute (sql) Print ("Record Deleted") @b.comait () Te ibeet BYTES + We use MySQL-Connector Python to connect MySQL. mysql.connector.connect() method of MySQL-Connector Python is used with the required parameters to connect MySQL. MySQL-Connector Python requires Python to be in the system's PATH. Installation fails iit does find Pho MySQLdb is an interface for connecting to 2 MySQL database server f implements the Pythor Database API and is built on top of the MySQL C API. ver from Python. It imple > Im order to put our new connection to good use, we need to create a cursor object. It gives us the abil le separate working environments through the same connection to the database. “ — | 7 i Y lity to have > OnceaDatabase Connectionis established, we are ready to create tables using execute() method ofthe created cursor > Read operation on any table means to fetch some useful information from the table > Use fetchall() method to fetch multiple values from a database table. > fetchone() fetches the next row of a ‘query result set. A result setis an object thats returned when a cursor object is used to query a table, > rowcount isa read-only attribute and returns the number of rows that were affected by an executel) method > UPDATE Operation on any database means to update one or more records, which are already available inthe table > To disconnect Database Connection, use close() method,

You might also like