Skip to main content

A self-contained Python driver for communicating with MySQL servers, using an API that is compliant with the Python Database API Specification v2.0 (PEP 249).

Project description

https://img.shields.io/pypi/v/mysql-connector-python.svg https://img.shields.io/pypi/pyversions/mysql-connector-python.svg https://img.shields.io/pypi/l/mysql-connector-python.svg

MySQL Connector/Python enables Python programs to access MySQL databases, using an API that is compliant with the Python Database API Specification v2.0 (PEP 249).

Features

Installation

Connector/Python contains the Classic and X DevAPI connector APIs, which are installed separately. Any of these can be installed from a binary or source distribution.

Binaries are distributed in the following package formats:

On the other hand, the source code is distributed as a compressed file from which a wheel package can be built.

The recommended way to install Connector/Python is via pip, which relies on WHEEL packages. For such a reason, it is the installation procedure that is going to be described moving forward.

Please, refer to the official MySQL documentation Connector/Python Installation to know more about installing from an RPM, or building and installing a WHEEL package from a source distribution.

Before installing a package with pip, it is strongly suggested to have the most recent pip version installed on your system. If your system already has pip installed, you might need to update it. Or you can use the standalone pip installer.

$ pip install mysql-connector-python

Installation Options

Connector packages included in MySQL Connector/Python allow you to install optional dependencies to unleash certain functionalities.

# 3rd party packages to unleash the telemetry functionality are installed
$ pip install mysql-connector-python[telemetry]

This installation option can be seen as a shortcut to install all the dependencies needed by a particular feature. Mind that this is optional and you are free to install the required dependencies by yourself.

Available options:

  • dns-srv

  • gssapi

  • webauthn

  • telemetry

Sample Code

import mysql.connector

# Connect to server
cnx = mysql.connector.connect(
    host="127.0.0.1",
    port=3306,
    user="mike",
    password="s3cre3t!")

# Get a cursor
cur = cnx.cursor()

# Execute a query
cur.execute("SELECT CURDATE()")

# Fetch one result
row = cur.fetchone()
print("Current date is: {0}".format(row[0]))

# Close connection
cnx.close()

HeatWave GenAI and Machine Learning Support

MySQL Connector/Python now includes an optional API for integrating directly with MySQL HeatWave’s AI and Machine Learning capabilities. This new SDK is designed to reduce the time required to generate proofs-of-concept (POCs) by providing an intuitive Pythonic interface that automates the management of SQL tables and procedures.

The new mysql.ai module offers two primary components:

  • GenAI: Provides implementations of LangChain’s abstract LLM, VectorStore, and Embeddings classes (MyLLM, MyVectorStore, MyEmbeddings). This ensures full interoperability with existing LangChain pipelines, allowing developers to easily substitute existing components with HeatWave-backed versions.

  • AutoML: Provides Scikit-Learn compatible estimators (MyClassifier, MyRegressor, MyAnomalyDetector, MyGenericTransformer) that inherit from standard Scikit-Learn mixins. These components accept Pandas DataFrames and can be dropped directly into existing Scikit-Learn pipelines and grid searches.

Note on Dependencies: These features introduce dependencies on langchain, pandas, and scikit-learn. To keep existing installations unchanged and the base connector lightweight, these dependencies are not installed by default. You must install them separately to use the mysql.ai features.

Example: GenAI Chatbot with Memory

This example demonstrates how to use MyLLM within a loop to create a simple chatbot that maintains conversation history.

from collections import deque
from mysql import connector
from mysql.ai.genai import MyLLM

def run_chatbot(db_connection, chat_history_size=5):
    # Initialize MyLLM with the database connection
    my_llm = MyLLM(db_connection)

    # Maintain a limited history for context
    chat_history = deque(maxlen=chat_history_size)
    system_msg = "System: You are a helpful AI assistant."

    while True:
        user_input = input("\nUser: ")
        if user_input.lower() in ["exit", "quit"]:
            break

        # Format history and invoke the LLM
        history = [system_msg] + list(chat_history) + [f"User: {user_input}"]
        prompt = "\n".join(history)

        # Invoke HeatWave GenAI
        response = my_llm.invoke(prompt)
        print(f"Bot: {response}")

        # Update history
        chat_history.append(f"User: {user_input}")
        chat_history.append(f"Bot: {response}")

# Usage
with connector.connect(user='root', database='mlcorpus') as db_connection:
    run_chatbot(db_connection)

Example: HeatWave AutoML in a Scikit-Learn Pipeline

This example shows how to use MyClassifier as a drop-in replacement within a standard Scikit-Learn pipeline.

import pandas as pd
from mysql import connector
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from mysql.ai.ml import MyClassifier

# 1. Setup Data (Pandas DataFrame)
X = pd.DataFrame([[0.5, 0.1], [1.0, 0.8], [0.1, 0.2]], columns=["feat1", "feat2"])
y = pd.Series([0, 1, 0], name="target")

# 2. Connect and Train
with connector.connect(user='root', database='mlcorpus') as db_connection:
    # Initialize the HeatWave classifier
    clf = MyClassifier(db_connection)

    # Create a standard Scikit-Learn pipeline
    pipe = Pipeline([
        ("scaler", StandardScaler()),
        ("mysql_clf", clf)
    ])

    # Fit the model (automates upload and training on HeatWave)
    pipe.fit(X, y)

    # Predict
    preds = pipe.predict(X)
    print(f"Predictions: {preds}")

    # Score
    score = pipe.score(X, y)
    print(f"Accuracy: {score}")

Additional Resources

Contributing

There are a few ways to contribute to the Connector/Python code. Please refer to the contributing guidelines for additional information.

License

Please refer to the README.txt and LICENSE.txt files, available in this repository, for further details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

mysql_connector_python-9.7.0-cp311-cp311-macosx_14_0_x86_64.whl (19.8 MB view details)

Uploaded CPython 3.11macOS 14.0+ x86-64

mysql_connector_python-9.7.0-cp311-cp311-macosx_14_0_arm64.whl (20.3 MB view details)

Uploaded CPython 3.11macOS 14.0+ ARM64

mysql_connector_python-9.7.0-cp310-cp310-win_amd64.whl (17.7 MB view details)

Uploaded CPython 3.10Windows x86-64

mysql_connector_python-9.7.0-cp310-cp310-manylinux_2_28_x86_64.whl (21.7 MB view details)

Uploaded CPython 3.10manylinux: glibc 2.28+ x86-64

mysql_connector_python-9.7.0-cp310-cp310-manylinux_2_28_aarch64.whl (21.9 MB view details)

Uploaded CPython 3.10manylinux: glibc 2.28+ ARM64

mysql_connector_python-9.7.0-cp310-cp310-macosx_14_0_x86_64.whl (19.8 MB view details)

Uploaded CPython 3.10macOS 14.0+ x86-64

mysql_connector_python-9.7.0-cp310-cp310-macosx_14_0_arm64.whl (20.3 MB view details)

Uploaded CPython 3.10macOS 14.0+ ARM64

File details

Details for the file mysql_connector_python-9.7.0-cp311-cp311-macosx_14_0_x86_64.whl.

File metadata

File hashes

Hashes for mysql_connector_python-9.7.0-cp311-cp311-macosx_14_0_x86_64.whl
Algorithm Hash digest
SHA256 5492d57a6a0e5127a928290737fbb91b66b46d31dac8de3e7604e550bf3b3a6e
MD5 45cd7d8919a6c5b498e5c126246232bb
BLAKE2b-256 a54bc45b8b601b0270faf1d4384e4c7270af9abb8d95ea39425253217c3c236c

See more details on using hashes here.

File details

Details for the file mysql_connector_python-9.7.0-cp311-cp311-macosx_14_0_arm64.whl.

File metadata

File hashes

Hashes for mysql_connector_python-9.7.0-cp311-cp311-macosx_14_0_arm64.whl
Algorithm Hash digest
SHA256 b5cb8a3ba42b539f79cd13e4c8376d28506f3180f7079c9b04ea7bfd0424fb03
MD5 d7ab5cbd140cc6a4324fadec40d15e89
BLAKE2b-256 70fababe981ec8c24eece7f47dc52c5e3fe3f126bc99cc80d637b49ac2fe50a4

See more details on using hashes here.

File details

Details for the file mysql_connector_python-9.7.0-cp310-cp310-win_amd64.whl.

File metadata

File hashes

Hashes for mysql_connector_python-9.7.0-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 c51be697bfdfdf63bb71c5ecc51f7c6faf4aaa3d14a0136fa16e97cc37df1185
MD5 37d07a214003ab4dba1fdee81b8ca822
BLAKE2b-256 50ee0be8e060376e518897f4b3433e768ccd05bc8bb3d08c436cc2441b44ac0b

See more details on using hashes here.

File details

Details for the file mysql_connector_python-9.7.0-cp310-cp310-manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for mysql_connector_python-9.7.0-cp310-cp310-manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 6546e0b60c275409a5add9e3308c3897fcf478d1338cd845b1664c1a8946f72f
MD5 5fefe6b98078a48d67560b14a6197170
BLAKE2b-256 f340f0184970f6483a4e5ffcb99028f8402f3789b885872a5779edd3fa53da44

See more details on using hashes here.

File details

Details for the file mysql_connector_python-9.7.0-cp310-cp310-manylinux_2_28_aarch64.whl.

File metadata

File hashes

Hashes for mysql_connector_python-9.7.0-cp310-cp310-manylinux_2_28_aarch64.whl
Algorithm Hash digest
SHA256 9bdfc2d4c4444cd1cc79cc6487c047b28fe2b26d0327b27eb9f5737bb553cb5c
MD5 bdf4b80d336df2858b3cf899d7533518
BLAKE2b-256 835c724577da77cd33d056ad48d1e29149f6c123371d651c0d824f6bfd2af28f

See more details on using hashes here.

File details

Details for the file mysql_connector_python-9.7.0-cp310-cp310-macosx_14_0_x86_64.whl.

File metadata

File hashes

Hashes for mysql_connector_python-9.7.0-cp310-cp310-macosx_14_0_x86_64.whl
Algorithm Hash digest
SHA256 a2f371ab69d65c61136c51ad7026017400166cef3c959cab7a9fb668c7acbfba
MD5 6b2b33c55555b6dafe02a50f3a710dbe
BLAKE2b-256 4340cba971fdc54522742955f12d4b019e9f3325d9a5c734abf5f012fde7cfff

See more details on using hashes here.

File details

Details for the file mysql_connector_python-9.7.0-cp310-cp310-macosx_14_0_arm64.whl.

File metadata

File hashes

Hashes for mysql_connector_python-9.7.0-cp310-cp310-macosx_14_0_arm64.whl
Algorithm Hash digest
SHA256 ee90c5f44f706f012be17f03f6ad158ff96e7f2dcc077896fe4537d3d28b3cf4
MD5 05e94ebe4733dd156d078f9af67f7cbc
BLAKE2b-256 7a7bbfbe1732bdc413fa29d4431e04f257bed32b0f3efe775ca2e70e9d347008

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page