![]() |
VOOZH | about |
MySQL is a open-source relational database for managing structured data. Integrating it with Python enables efficient data storage, retrieval and manipulation within applications.
To work with MySQL, we use MySQL Connector, a driver that enables seamless integration between the two. It handles the conversion between Python and MySQL data types and is implemented in pure Python, requiring no third-party dependencies.
To install the Python-mysql-connector module, one must have Python and PIP, preinstalled on their system. If Python and pip are already installed type the below command in the terminal.
pip3 install mysql-connector-python
Note: If Python is not present, go through How to install Python on Windows and Linux? and follow the instructions provided.
π python mysql connector installWe can connect to both local and cloud-based MySQL databases using the connect method of mysql-connector library.
Example: Connecting to Local MySQL Database
Output
<mysql.connector.connection_cext.CMySQLConnection object at 0x7f73f0191d00>
Note: For more information, refer to Connect MySQL database using MySQL-Connector Python.
After connecting to the MySQL server let's see how to create a MySQL database. For this, we will first create a cursor() object and will then pass the SQL command as a string to the execute() method. The SQL command to create a database is -
CREATE DATABASE DATABASE_NAME
Example: Creating MySQL database
Output
π Pyhton mysql create databaseFor creating tables we will follow writing the SQL commands as strings and then passing it to the execute() method of the cursor object. SQL command for creating a table is -
CREATE TABLE
(
column_name_1 column_Data_type,
column_name_2 column_Data_type,
:
:
column_name_n column_Data_type
);
Example: Creating MySQL table
Output
π create table python mysqlTo insert data into the MySQL table Insert into query is used.
Syntax:
INSERT INTO table_name (column_names) VALUES (data)
Example 1: Inserting Single Row
Output
π insert 1 row in mysql database using PythonExample 2: Inserting Multiple Rows
To insert multiple values at once, executemany() method is used. This method iterates through the sequence of parameters, passing the current parameter to the execute method.
Output
π python mysql insert many rowsWe can use the select query on the MySQL tables in the following ways -
In order to select particular attribute columns from a table, we write the attribute names.
SELECT attr1, attr2 FROM table_name
In order to select all the attribute columns from a table, we use the asterisk β*β symbol.
SELECT * FROM table_name
Example: Select data from MySQL table
Output
π python mysql select queryWhere clause is used in MySQL database to filter the data as per the condition required. You can fetch, delete or update a particular set of data in MySQL database by using where clause.
Syntax:
SELECT column1, column2, β¦. columnN FROM [TABLE NAME] WHERE [CONDITION];
Example: Where clause in MySQL
Output
('Rohan', 'MAE', 43, 'B', 20)
('Amit', 'ECE', 24, 'A', 21)
('Anil', 'MAE', 45, 'B', 20)
('Megha', 'ECE', 55, 'A', 22)
OrderBy is used to arrange the result set in either ascending or descending order. By default, it is always in ascending order unless βDESCβ is mentioned, which arranges it in descending order. βASCβ can also be used to explicitly arrange it in ascending order. But, it is generally not done this way since default already does that.
Syntax:
SELECT column1, column2
FROM table_name
ORDER BY column_name ASC|DESC;
Example: Order By clause in MySQL
Output
π python mysql ordery byLimit clause is used to control or limit the number of records in the result set returned from the query generated. By default, it gives out the required number of records starting from the top but it allows the use of OFFSET keyword. OFFSET allows to start from a custom row and get the required number of result rows.
Syntax:
SELECT * FROM tablename LIMIT limit;
SELECT * FROM tablename LIMIT limit OFFSET offset;
Example: Limit Clause in MySQL
Output
('Nikhil', 'CSE', 98, 'A', 18)
('Nisha', 'CSE', 99, 'A', 18)
Update query is used to change the existing values in a database. By using update a specific value can be corrected or updated. It only affects the data and not the structure of the table.
Syntax:
UPDATE table_name
SET column1 = new_value1, column2 = new_value2, ...
WHERE condition_column = condition_valu
Example: Update MySQL table
Output
π python mysql update tableWe can use the Delete query to delete data from the table in MySQL.
Syntax:
DELETE FROM TABLE_NAME WHERE ATTRIBUTE_NAME = ATTRIBUTE_VALUE
Example: Delete Data from MySQL table
Output
π python mySQL delete from tableDrop command affects the structure of the table and not data. It is used to delete an already existing table. For cases where you are not sure if the table to be dropped exists or not DROP TABLE IF EXISTS command is used.
Syntax:
DROP TABLE tablename;
DROP TABLE IF EXISTS tablename;
At first, let's see the list of tables in our database.
π python mysql drop tablesWe can see that there are two tables for students, so let's drop the second table.
Example 1: Drop Table in MySQL
Output
π python mysql drop tablesExample 2: Drop Table if exists
The above example, will not create any error and output because we have used the Drop Table is exists query. If we will simply use the Drop table Employee then ProgrammingError: 1051 (42S02): Unknown table 'gfg.Employee' is raised.