Home > Database > Mysql Tutorial > How to Connect to MySQL with Python 3 on Windows After mysqldb's Deprecation?

How to Connect to MySQL with Python 3 on Windows After mysqldb's Deprecation?

Barbara Streisand
Release: 2024-12-09 13:59:13
Original
359 people have browsed it

How to Connect to MySQL with Python 3 on Windows After mysqldb's Deprecation?

How to Connect to MySQL with Python 3 on Windows

Connecting to a MySQL database is a critical aspect of Python programming tasks. For Python 3 users on Windows, the mysqldb module has been a popular choice. However, it's important to note that mysqldb is no longer available for Python 3.

Alternative Options for Python 3 Connection

Fortunately, there are several alternative options available to connect to MySQL with Python 3 on Windows:

  • mysql-connector-python: The officially supported Oracle library that offers pure Python connectivity. It is a bit slower compared to other options.
  • pymysql: Another pure Python library that is faster than mysql-connector-python and offers high compatibility with MySQLdb.
  • cymysql: A fork of pymysql that includes optional C speedups for improved performance.
  • mysqlclient: Django's recommended library, a friendly fork of the original MySQLdb that aims to restore compatibility. It is the fastest option due to its C-based implementation.

Specific Binary Repository

Unfortunately, there is no specific binary repository where you can find pre-built binaries for these modules. Instead, you should install them using the package manager pip, which is included in ActiveState Python 3. For example, to install mysqlclient, you can run the following command:

pip3 install mysqlclient
Copy after login

Connecting to MySQL

Once you have installed one of the alternative modules, you can connect to a MySQL database using Python 3:

import mysqlclient

# Establish a connection
connection = mysqlclient.connect(
    host="localhost",
    user="username",
    password="password",
    database="dbname",
)

# Execute a query
cursor = connection.cursor()
cursor.execute("SELECT * FROM table_name")

# Retrieve the results
results = cursor.fetchall()

# Close the connection
connection.close()
Copy after login

By following these steps, you can easily connect to MySQL using Python 3 on Windows.

The above is the detailed content of How to Connect to MySQL with Python 3 on Windows After mysqldb's Deprecation?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template