A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://pynative.com/python-mysql-tutorial/ below:

Python MySQL Database Connection - MySQL Connector Python

In this lesson, you will learn how to connect the MySQL database in Python using the ‘MySQL Connector Python‘ module. This Python MySQL tutorial demonstrates how to develop and integrate Python applications with a MySQL database server.

In Python, We can use the following modules to communicate with MySQL.

Note: Above all interfaces or modules are adhere to Python Database API Specification v2.0 (PEP 249) that means the syntax, method, and way of access the database is the same in all.

PEP 249 is designed to encourage and maintain similarity between the Python modules that are used to access databases. By doing this, above all modules are following rules defined in Python Database API Specification v2.0 (PEP 249).

You can choose any of the above modules as per your requirements. The way of accessing the MySQL database remains the same. I recommend you to use any of the following two modules:-

  1. MySQL Connector Python
  2. PyMySQL

Note: This tutorial focuses on the MySQL Connector Python module. All examples are created using MySQL Connector Python.

Advantages and benefits of MySQL Connector Python: –

How to connect MySQL database in Python

Let’s see how to connect the MySQL database in Python using the ‘MySQL Connector Python’ module.

Arguments required to connect

You need to know the following detail of the MySQL server to perform the connection from Python.

Argument Description Username The username that you use to work with MySQL Server. The default username for the MySQL database is a root. Password Password is given by the user at the time of installing the MySQL server. If you are using root then you won’t need the password. Host name The server name or Ip address on which MySQL is running. if you are running on localhost, then you can use localhost or its IP 127.0.0.0 Database name The name of the database to which you want to connect and perform the operations.

How to Connect to MySQL Database in Python

  1. Install MySQL connector module

    Use the pip command to install MySQL connector Python.
    pip install mysql-connector-python

  2. Import MySQL connector module

    Import using a import mysql.connector statement so you can use this module’s methods to communicate with the MySQL database.

  3. Use the connect() method

    Use the connect() method of the MySQL Connector class with the required arguments to connect MySQL. It would return a MySQLConnection object if the connection established successfully

  4. Use the cursor() method

    Use the cursor() method of a MySQLConnection object to create a cursor object to perform various SQL operations.

  5. Use the execute() method

    The execute() methods run the SQL query and return the result.

  6. Extract result using fetchall()

    Use cursor.fetchall() or fetchone() or fetchmany() to read query result.

  7. Close cursor and connection objects

    use cursor.clsoe() and connection.clsoe() method to close open connections after your work completes

MySQL database connection in Python

Run the below query on the MySQL console if you have not created any database in MySQL. Otherwise, you can skip the below query.

Create Database in MySQL

Create database Electronics;Code language: Python (python)

Example to connect to MySQL Database in Python

Output.

Connected to MySQL Server version  5.7.19
You're connected to database:  ('electronics',)
MySQL connection is closed

Points to remember

Create MySQL table from Python

Now you know how to connect to a MySQL server from Python, In this section, we will learn how to create a table in MySQL from Python. Let’s create table ‘Laptop’ under the ‘Electronics’ database.

Output:

Laptop Table created successfully 
MySQL connection is closed
Python MySQL CRUD Operation

Also, learn how to execute various MySQL operations from Python by referring to the following articles.

Click on each tutorial to study operations in detail.

Python MySQL Connection arguments list

We already discussed the four mandatory arguments required to connect the MySQL Server.

Let see what other connection arguments we can use to communicate with the MySQL server from Python. Below is the list of all other connection arguments and their meaning.

Use the Dictionary to keep MySQL Connection arguments

Furthermore, let see how to use a dictionary to store all of these connection arguments.

If you have lots of connection arguments, it’s best to keep them in a dictionary and use the ** operator.  for example, you know you require a minimum of four arguments  (i.e., username, password, hostname, database name) to connect MySQL.

If you have lots of connection arguments, it’s best to keep them in a dictionary and use the ** operator. In exceptional cases, we need more than four arguments in the connect method to connect the MySQL database. Let’s understand this. For example, below are three more connection arguments we can use in the connect() method.

  1. connection_timeoutTimeout for the TCP and Unix socket connections
  2. auto_commit – Whether to auto-commit transactions. The default is false
  3. pool_size – Connection pool size if you want to use connection pooling.

You can use many other connection arguments as per your need, add them all in a dictionary, and pass a dictionary to connect() method. Let’s demonstrate it in the below example.

Change MySQL Connection Timeout from Python

Sometimes we need to change the connection timeout value if we read or insert extensive data to the MySQL server. Connection terminates if the request takes more time than this value.

Use a connection_timeout argument of MySQL connector Python to manage the timeout issues by increasing the timeout value.

The connection_timeout is the timeout value in second for the TCP and Unix socket connections. This time denotes the number of seconds the MySQL server waits to fulfill the current request.

You can also set the following Parameters of the MySQL server by executing SQL query from Python to handle the connection timeout issue. Change the following parameters’ value only when the connection_timeout argument alone can’t control the timeout issue.

Example

As you can see, I have set all connection timeout values to 180 seconds, i.e., 3 min in the above program.

Connect to MySQL Using Connector Python C Extension

Python connector module has a C Extension interface to connect the MySQL database. The use_pure connection argument determines whether to connect to MySQL using a pure Python interface or a C Extension.

The default value of use_pure is False means it uses the pure Python implementation to connect that we already discussed. The below example demonstrates how to connect using a C extension.

Next Steps:

To practice what you learned in this article, Please solve a Python Database Exercise project to Practice and master the Python Database operations.

I have created a Hospital Information System exercise using Python and MySQL. This Exercise has six questions. I have provided the required tables so you can proceed directly to solve the problems of this Exercise.

That’s it, Folks. Let me know your comments in the section below.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4