This tutorial will help you to learn how to use MySQL with Python.
Introduction:
Python MySQL Connector is used to enable python programs to access MySQL databases using API.
In Python, you need to install a Python MySQL Connector to interact with MySQL database. You can get it with PIP:
> pip install mysql-connector-python
Open command prompt and run the above command to install Python MySQL Connector.
Test your connector is successfully installed or not with below program.
Run the above code if you see errors means connector driver were not properly installed.
General Steps:
Connect to the MySQL server with existing DB or newly created DB.
Execute a SQL query or fetch results.
Close the connection to the MySQL server.
Establish Connection:
To establish connection between Python and MySQL Server we use mysql.connector.connect() method.
Note: In the above program, the passwd parameter value is the password of MySQL Server.
Creating Database:
Creating a cursor object is used to execute SQL queries.
The following program is the example for establish connection with existing database.
Executing Queries:
execute() - This method accepts a MySQL query as a parameter and executes the given query.
Example: The following example shows how to create student table.
Tables in college database
('student',)
Student table description
('rollno', 'varchar(11)', 'YES', '', None, '')
('name', 'varchar(30)', 'YES', '', None, '')
Example: The following example shows how to insert record into student table.
1 record inserted.
executemany() - This method accepts a list series of parameters list. Prepares an MySQL query and executes it with all the parameters.
Example: The following example shows how to insert multiple records into student table.
2 records inserted.
Fetch Records:
fetchone() - This method fetches the next row in the result of a query and returns it as a tuple.
The following example shows how to extract one record from student table.
('501', 'nani')
fetchmany() - This method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row.
The following example shows how to extract many records from student table.
[('501', 'nani'), ('502', 'siva parvathi')]
fetchall() - This method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones).
The following example shows how to extract all records from student table.