Python – mysql connectivity revision notes outlines the steps to connect a Python application to a MySQL database:
1. Import the mysql.connector module and use it to create a connection object using host, user, password, and database details.
2. Create a cursor object from the connection to execute SQL queries.
3. Use the cursor's execute method to run queries, and fetchall or fetchone to retrieve and store results in Python variables.
4. For queries that modify data, commit the changes to save to the database.
Python – mysql connectivity revision notes outlines the steps to connect a Python application to a MySQL database:
1. Import the mysql.connector module and use it to create a connection object using host, user, password, and database details.
2. Create a cursor object from the connection to execute SQL queries.
3. Use the cursor's execute method to run queries, and fetchall or fetchone to retrieve and store results in Python variables.
4. For queries that modify data, commit the changes to save to the database.
Python – mysql connectivity revision notes outlines the steps to connect a Python application to a MySQL database:
1. Import the mysql.connector module and use it to create a connection object using host, user, password, and database details.
2. Create a cursor object from the connection to execute SQL queries.
3. Use the cursor's execute method to run queries, and fetchall or fetchone to retrieve and store results in Python variables.
4. For queries that modify data, commit the changes to save to the database.
mysql.connector is the module which needs to be imported so that we can use it’s function connect() to create a connection object con1. It initializes the driver between python and mysql with the four parameters ie. server host, mysql user, password and database of mysql Step 2 - con1=ms.connect(host="localhost", user="root", passwd="", db="busdb") to execute the sql queries, we need to create a cursor object which has the execute() function. The cursor object is created with the help of cursor() function that belongs to connection object con1 Step 3 - cur1=con1.cursor() biid=int(input("Enter the bus id: ")) sql="select * from bus where bid=%s" val=(biid,) Step 4 - cur1.execute(sql,val) Now, to retrieve the data collected in the cursor object cur1, the fetchall() or fetchone() (which belongs to cursor object cur1) is used to store in a python object. Step 5 p=cur1.fetchall() # list of tuples p=cur1.fetchone() # a tuple if the sql query is a DML statement (insert/ delete/ update), then it is compulsory to use commit() Step 6 - con1.commit() to save the changes made in the database. n=cur1.rowcount() n will have the number of rows affected by the execute() function