Page 1 - Interface Python With SQL
P. 1

Interface Python with SQL


               NEED
                     Databases play a very vital role in the working of an organization. Databases works using
                       SQL.
                     Python supports application program development.
                     Real life applications need to manipulate data stored in a database, through an application
                       designed by a user/programmer.
                     Databases play a very vital role in the working of an organization. Databases works using
                       SQL.
                     Python supports application program development.
                     Real life applications need to manipulate data stored in a database, through an application
                       designed by a user/programmer.


               Steps for creating database connectivity applications:
                   1.  Start Python
                   2.  Import mysql.connector package/ import pymysql
                   3.  Open a connection to MySQL database (using connect function)
                   4.  Create a cursor instance/object
                   5.  Execute SQL query through cursor instance/object
                   6.  Extract data from resultset
                   7.  Clean the environment


               Opening a connection to MySQL database


               connect() function of mysql.connector establishes the connection

               Syntax:
               <connection-object> = mysql.connector.connect(host=<host-name>, user=<username>,
               passwd=<password>, [database=<database>])

                   •   User is the username on MySQL
                   •   Password is the password of the specified user
                   •   Host-name is the database server name
                   •   Database(optional) is the name of the MySQL database.


               Example:
               import mysql.connector
               mydb = mysql.connector.connect (host="localhost", user="root", passwd="1234")
               (connection will be to root, no active database)

               OR

               import mysql.connector as pysql
               mydb = pysql.connect (host="localhost", user="root", passwd="1234", database="School")
               (active database is School)
   1   2   3   4