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

Inteface python with mysql

Very helpful

Uploaded by

dhdrdi6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
21 views

Inteface python with mysql

Very helpful

Uploaded by

dhdrdi6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 13
In This Chapter 14.1 Introduction 14.2 Connecting to MySQL from Python 14.3. Parameterised Queries 14.4 Performing INSERT and UPDATE Queries 4.1 Introduction yout design real-life applications, you are bound to | eerie situations wherein you need to manipulate data OTE Tepd in a database through an application designed by you. Before you start working with a ‘are developing Python applications, in this chapter Python mysql connector, you need Since Jo ee will be based on how you can connect to a ‘0 install iton your computer. Both pip and Conda installation of Python MySQL database from within a Tee MySQL. connector is given in + to connect to a database from within Python, you __ Appendix Co this Book. So, please provides connectivity functionality. There refer to Appendix C for the installation of the same. in orde need a library that : me mnany different libraries available for Python to complis this. We shall work with mysql connector library {for the same. at ns 14.2 connecting to MySQL from Python - have installed Python MySQL connector (as per Appendix C), you can write Python Sips using MySQL.connector library that can connect to MySQL: databases from within 541 42 COW VUTER SCIENCE WITH PYTHON — yy 14.2.1. Steps for Creating Database Connectivity Applications There are mainly seven steps that must be followed In order to create a database connectivity application. Step1 Start Python. Step 2 Import the packages required for database programming. Step 3 Open a connection to database, Step 4 — Create a cursor instance. Step5 Execute a query, Step 6 Extract data from result set, Step 7 Clean up the environment. Let us talk about these steps in details. Step_1) Start Python Start Python’s editor where you can create your Python scripts. It can be IDLE or Spyder IDE — whatever you feel comfortable in, (iep 2. Import mysql.connector Package First of all you need to import mysql.connector package in your Python scripts by using command : Amport mysql. connector ee Vo cone any lef of your hace import mysql. connector as sqLtor You can also use pymysql in place of mysql.connector for connecting with MySQL database. We shall talk about this in section 14.2.2. ep 3. Open a Connection to MySQL Database Next you need to establish connection to a MySQL database using connect( ) function of mysql.connector package. ‘The connect( ) function of mysql.connector establishes connection to a MySQL database and requires four parameters, which are : = mysql. connector. connect (host = , user = , passwd = [, database = ]) ‘= user is the username on MySQL = password is the password of the user = Jtost-name the database server hostname or IP address = database is optional which provides the database name of a MySQL. database, Specify a Python identifier as name. You shall be using this name for executing queries and for other tasks on connected database. For example : loginid and password of your MySQL database | Amport mysql. connector as sqltor \ | ‘The comsection > RON = sqltor .connect (host = "localhost", user= "root", passwd = "MyPass", object database=“test) ssc dtabue prac PYTHON WITH MyScL 543 yan ye oo mysghconnector package as imported Saltor, we are using the name sqltor in place of (gjnet ctor, Hf you have Imported the package as is . sear mysql.connector Jr ged to write above function as Se fn mysqieconnector. connect (host » "localhost", user = *root*, Passd = "MyPass", database = "test”) command will establish connection to MySQL database with user as “root”, das”MyPass” and to the MySQL database namely test which exists on the MySQL. ou must ensure thatthe user and password that you specify ae valid user and password Her ea MYSOL installation, pee Ps for 4 ; it means you have s full [connection Oxect thon reports 0 error, i y seer wpFytn’d to MySQL database. You can also check for A database Connection object controls the connection to the Cag tion using function is i ful connection using function is connected( ) with ‘ sents. 2 unique Bde object (Which returns True, if connection is semonitna datonaue connected ful, ie, if you may write following additional code from within a script/program. suet if the connection fs successful or not to The sae connection object with which we senycon.4s_connected(): rari fa MyBO otabone print( ‘Successfully Connected tomysQL database’ ) allowing screenshot shows you the output produced by code shown below : rt mysql.connector as sqltor rycon= sqltor.connect (host = "localhost", user = "root", passwd = "MyPass”, database ="test") 4¢mycon.is_connected(): print ( ‘Successfully Connected to MySQL database’) & = eae a Co) conse ql.connector a8 .execute() For example, if you want to view all the records of table data which is a table in the databace ] test to which you established connection in step 2, you can execute SQL query “select * fo, data” by writing : = } cursor.execute("select * from data") coe ot pera 2 ee sat ate hte ‘The above code will execute the given SQL query and store foo the retrieved records (ie, the resultset) in the cursor object the’ result (namely cursor) which you can then use in your gf ecards that ae fase programs/scripts as required. “the database by ecg eel query and made avaliable to the Step 6. Extract Data from Resultset See ea a You will need this step (step 6) if you have retrieved records from the database using SQL SELECT query and need to extract records from the retrieved resultset, Once the result of query is available in the form of a resultset stored in a cursor object, you can extract data from the resultset using any of the following fetch...() functions. ( = -fetchall( ), It will return all the records retrieved as per query in tuple form (ie., now will be a tuple.) (ii) = fetchone( ). It will return one record from the resultset as a tuple or a list. First time it will return the first record, next time it will fetch the next record and so on. This method returns one record as a tuple : if there are no more records then it retums None. (ii) = .fetchmany(). This method accepts number of records to fetch and returns a tuple where each record itself is a tuple. If there are not more records then it returns an empty tuple. (iv) = .rowcount. The rowcount is a property of cursor object that “returns the number of rows retrieved from the cursor so far. Following examples will } make it more clear. INTERFACE PYTHON WITH MySQL 545 on w see with following code examples how these functions work. For the following code ie wwe shall be connecting to database test, table student that has the following data in it gudent of MYSOL database fest te Rolin | Name | Marks | Grade | Section | Project 101_| Ruhani_| 7680 "aed oA Pesidin 102_| George | 71.20 B (ema scence’ 3 103 | Simran | 81.20 ‘A ie weaned | 104__| Ali 61.20 B (cis liKwigred 105 | Kushal | 51.60 C ‘aaah levine 106__| Arsiya 91.60 At B | Submitted 107 Raunak | 3250 F age | Goumaincs code examples assume that the connection to the database has been established ) method of mysql.connector as discussed in earlier steps. That is, all the examples of fetch functions have following code pre-executed for them = ilowing ‘ag connect( de Jowing CO" ies mysql.-connector as sqltor connect (host = "localhost", user = "root", passwd = "MyPass”, database = "test”) s¢nycon.is_connected() => False: "Error connecting to database’ print(’Error con 1 toMySOL database’) rye SOL query revives all the data of aycon.cursor() ‘able student of database test uute("select * from student”) that in addition to above code how all fetch.,() methods will behave. cursor = cursor -exect Letus now see she fetchal() method re feehali() method wil retum all the rows from the results in the form of a tuple containing the Fecords ‘¢database connected established and cursor object created » data cursor.fetchall() ¢ ach he rc te sue ¢ ursor.PoWCOUNt <——— How many records returned by SOL query in the resultset a tle (a tule of Peart ea arucares print(row) (one row ofa time ‘The output produced by above code is : qotal number of rows retrieved in resultset : 7 << Result of eursor.roweount (oi, ‘Ruhani”, Decimal(*76.80"), ‘A’, ‘A’, ‘pending’) 02, Decimal(*71.20"), ‘B’, ‘A’, submitted") 103, Decimal(*81.20'), ‘A’, “Evaluated") (ios, ‘Ali?, Decimal (‘61.20"), ‘8’, ‘c’, ‘Assigned’) | *—— cursorfetchall 's rexut (0s, ‘Kushal’, Decimal(‘51.60"), ‘C’, ‘C’, *Evaluated’) was stored in data, which is (106, ‘arsiya’, Decimal(‘91,60"), ‘A+’, ‘B", ‘Submitted”) se ret cre Pr (107, *Raunaq’, Decimal (‘32.50’), ‘F* » ‘Submitted’) — | 546 COMPUTER SCIENCE WITH PHN (Hi) The fetchmany( ) method The fetehmany() method will return only the <> number of rows from the resultset in ty form of a tuple containing the records. ~ # database connected established and cursor object created a orca acucsog Fecchmany( 4) .close( ) ‘eg., we established the database connection via connection object mycon above, So We shall write : ‘mycon.close( ) Following example lists the complete code wherein only first three records of the database table student of MySQL database test are listed row by row. COMPUTER SCIENCE WITH PYTHON m 1421 write a Pytnon program that displays frst three rows fetched from student table of MySQL database est’ rogram (Note. user is “learner import mysql. connector as sqltor nd password is “fast”) nycon = sqltor.connect (host = "localhost", user = "learner", passwd ="fast", database =“test~) if mycon.is_connected() == False: print('Error connecting to MySQL database’) cursor = mycon. cursor() cursor. execute("select * from student data = cursor. fetchmany (3) count = cursor. rowcount for row in data : print (row) mycon.close() The output produced by above code is : 01, ‘Ruhani', Decimal(‘76.80"), ‘A’ (102, ‘George’, Decimal(‘71.20’), ‘B (203, ‘Simran’, Decimal(‘81.20"), 14.2.2 Connecting with MySQL Database using pymysql ‘a’, ‘Pending’) ‘a", ‘Submitted’ ) ‘a’, ‘B', ‘Evaluated’) So now you know how to connect with a MySQL database from within a Python program, But so far you have used mysql.connector for this. You can also use pymysql library for connecting with a MySQL database, which we are going to discuss in this section. The basic difference between mysql.connector and pymysq] is that the mysql.connectoris made available by Oracle, which owns MySQL, and the pymysql library is made available by Python (itis pure Python). Thus, you can choose to work with any of these for connecting with MySQL. Inorder to use pymysq] in your Python program, you need to follow the steps as given below Step 1 Start Python Step 2 Import pymysql by giving the following statement : import pymysql as pym Step 3 Connect to a MySQL database by giving a statement as per the following syntax : = pymysql.connect("localhost", , , ) For example, User name é a mycon = pym.connect(“localhost™, "root™, “MyPass”, “School” ) AS Connection name x Password Name of the MySOL database to which connection is being established wa NTIRACE PINON a he steps, Le, steps 4,5, 6,7 are identical to what you have learn allowing example progeam te imp! ling example 14,1 given But please note that connection object created ale va esl Asin fuk pre sr Pitino te socelon Tie wx ot coe th pO ‘example - une it withe pymnyeep pest of! ection: Fo mysal: Write a Python prog three ranws fetched frat student tabi yest’. Use pymysql to comect with the database Note. set Ik “earner an the password a “tay amport pymysal as Pym ayean pym.connect("Localhost", "learner, “fast*, “test") qursor = mycon.curson() cursor execute("selact * from student") | «cursor. fetchmany(3) | dat count = cursor. rowcount Ne ee ae is for rowin data ! wie print(row) ycon,c10se() ‘The outpul produced by above code is tquhani", decimal ('76.80'), ‘A’, ‘A’, ‘Pending') fa02) "se0rge’ pecinat(‘71.20"), ‘B', ‘A’, ‘Submitted’) * pecimal('81.20'), ‘A', ‘'B', ‘Evaluated’ sis program will also produce the same output as the previous example progeam 143 parameterised Queries section, you learnt about how you can execute simple SQL queries after establishing, InFrecton to MySQL database, But SQL queries that were used, were simple queries Sometimes, you may need to run queries which are based on some parameters of values that you provide from outside, inp = 78 i SELECT * FROM student WHERE MARKS > inp 5 In previous imysa).connector uch queries are called parameterised queries, To execute parameterised queries i 19, Let us talk aneetion, you need to form SQL. query strings that include values of pararete ; about how you can form such query strings. Forming Query Strings j Note, for all the following code examples, MySQL database fest, the one we have used earlier. The connect the cursor object name is cursor as earlier. ‘we are again connecting to the student table of ion object name is mycow art eae ay a 0 COMPUTER SCIENCE WITH PrTicy, er) ‘That is, the code for connection is import mysql. connector as sqltor sycon = saltorconnect(host« "localhost", user « learner", passwd = “fast, databar «up if mycon.{s_connected() == False: st) print ("Error connecting to MySQL database’) cursor = mycon.cursor() Let us now discuss about how you can form parametrised query strings. To form que; ‘i TY strin, based on some parameters, you can go for one of the following fwo methods: "Bs () Old Style : String Templates with % formatting In this style, string formatting uses this general form: £% v where f is a template string and v specifies the value or values to be formatted isin, template. If multiple values are to be formatted, v must be a tuple: For this you can, 8 at i ipl wit SOL query ina string but use a %s code in place ofthe wae to be provided aaa pars For example, é “select * from student where marks > Xs" <—— oes eats oo ndetads ‘and its The above string is an incomplete string (only f, no %v here) as it contains a Placeholder Parameter as %e, but its parameter value is not provided here. To complete it, y must provide a tuple of values with% prefixed to itnext to the string (called the value tuple, % 9, ©8» if'you want to provide value 70 for %s placeholder in above query string, you can form ike value tuple as follows : (70, ) <—— For single value tobe stored ina up, comma must follow it Now you can complete the above SQL query string as follows : select * from student where marks > %s" %(70,) f v Now you can store this query string in variable and then execute that variable through cursor.execute( ) method’as shown below : # database connected established and cursor object created st = "select * from student where marks > Xs" ‘%(7,) ene a cursor. execute( st ) Lf a eI data = cursor.fetchall() Do not forget to enclose for row in data ith, / Placeholder % in quotes for sting print (row) ‘ | _Barameters in string template 101, ‘Ruhani’, Decimal(‘76.80"), ‘A’, ‘A’, ‘Pending’) (102, ‘George’, Decimal(‘71.20"), ‘B’, ‘a’, ‘submitted’) 203, ‘Simran’, Decimal(*81.20"), ‘a’, ‘a’, “Evaluated") © (106, “arsiya’,, Decimal(*91.60"), ‘At, “B", ‘submitted') VO3 ah emoe: ¥ RFACE PYTHON WITH My! jac intel SQL 551 i ner, the at epee may add multiple parameter values, but one caution you must thal get to enclose placeholder %s in quotes for string parameters ¢8: exercise IS database connected established and cursor object created om c e, Ms" enclosed in ques for sring value “select * from student where marks > Xs and section = '%s' " % (78, "B’) a . cursor. execute (st) gata = cursor. fetchall() Kecaeae wee for row in data : print(row) ", ‘Evaluated’) 8", Submitted") aos, ‘sinfan’ pecimal('81.20’), ‘A’ fans, ‘arstya"s Decimal(‘91.60'), ‘At’, Injematively you can provide the tuple with the exeeute() function 05: cursor .execute(, ) eg ram = 20 id=2 input = (ram, id) ~ query = “Update computers set ram =%s where id = a i cursor-execute(query , input) now Sie: String Templates with { } formatting The new style of creating SQL query strings involves the use of the format( ) method of the str fetus first understand this with a normal string and then we shall apply it on SQL query rings. The general form for using format is: template. format (P@, Pl, «++» k@ = ve, ki=v1, . The template is a string containing a mixture of one or more format codes embedded in fonstant text. The format method uses its arguments to substitute an appropriate value for each format code in the template. az ‘The arguments to the .format( ) method are of two types, The list starts with zero or more positional arguments p, followed by zero oF more Keyword arguments of the form kv; where each k; is a name with an associated value 2,.. - Consider following example. In this example, the format code “(0)” is replaced by the first positional argument (49), and “(1)” is replaced by the second positional argument, the string “okra” sii These are place holders Values ple V. Values are aah ieee site “ arise from here wwe have {0} hectares planted to {1}." -format ‘COMPUTER SCIENCE wry Poy a The above string template will yield following string ‘We have 49 hectares planted to okra. The values are picked from the values tuple V from left 10 right, ic, the first valug be placed in the first | placeholder, second value in the second [/ Placeholder, ar, dP ny You may even skip the numbers 0,1 in (). That is, following string will ge vieleee string as above. the ong “We have (} hectares planted to {} ." .format (49, okra") In the next example, we supply the values using named arguments, The argumen supplied in any order. The keyword names must be valid Python names, eg, May by Values tape VV a subtitled ror et “{monster} has eaten {city}".format(city ='Tokyo", monster =" Tsunami) In the above string template {monster} and {city} are named arguments, Named argu replace the value of the arguments as per the names not as per the order So even thers values tuple above, the first value is city =Tokyo’, it will not replace the first placeho| Bh in, rather it will replace the placeholder having its name ie,, {city Merton So the string generated will be : “Tsunami has eaten Tokyo Based on above information, you can create your SQL query strings. Again, make sur enclose a string value place holder in quotes, ie., as “{ },]. to Now consider following example : St = "select * from student where marks > {} and section = "{}' “.format(70, "By The above query string st stores : Place holder enclosed ig a “select * from student where marks > 7@ and section = 'B"" And it will yield the same query result as earlier. 14.4 Performing Insert and Update Queries — Since INSERT and UPDATE are also SQL. commands, you can execute them just the way you have executed SELECT queries earlier. Thatis, store the query in astring as a simple query oras a parameterised query and execute it using cursor.execute( ) method. BUT one important thing you must ensure with INSERT and UPDATE queries (which make changes to the database unlike SELECT) you must commit your query after executing INSERT and UPDATE queries. 44 cINTERFACE PYTHON WITH MySQL this your must run commit() method of connection in the end ie For fon object>..conmit( ) connects seis dane to reflect the change in the database physically following examples (assuming that connection has been established with student table of test database as earlier ; the connection object is mycon and the cursor object name is query example “INSERT INTO student(rollno, name, marks, grade, section) VALUESCIDs. Ch o-C}. Ch) 4)*)" "Format (tes, “eka”, 84.0, “A, cas qursor.execute(st) rycon cont) curso") (p INSERT te an ran a SELECT query t0 check if your data has been added to the table or not. ATE query example Ne a you (our. ‘st = "UPDATE student seT marks = {} Please note, you need to run oe wmiene marks = {)"-format(77, 76-8) ee reams cursor.execute(st) the database table 30 that changes ate reflected in the database. vita ycon.conmit() S@ anner, you can also run DELETE queries, but DO NOT forget to commit( ) after ee ehe query. (Refer to solved problem 10 that executes a DELETE query) have come to the end ofthis chapter. Let us quickly revise that we have leamt so sait far. . a. fr USI ye a «ee 4 To ‘connect toa database from: within a programming application, you need a framework that facilitates communication between two. different generes of software (programming application and DBMS). = To connect from Python to MySQL, you need a library called ‘mysql connector. 4 You must import mysql.connector in the Python progranvscript before writing code for connectivity. 4 Steps to create a database connectivity Python application are : | Step 1. Start Python, — : ‘Step 2. Import the packages required for database programming. "Step 3. Open a connection. ‘Step 4 Create a cursor instance. 7 Step 5 Execute a query. "5 “Step 6 siract data from result set "Step 7 Clean up the environment. he est laa

You might also like