### Install Connector/Python using pip Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/installation.md This is the recommended method for installing Connector/Python. Ensure you have a recent version of pip installed. ```bash shell> pip install mysqlx-connector-python ``` -------------------------------- ### Install MySQL Connector/Python with Compression Source: https://context7.com/mysql/mysql-connector-python/llms.txt Install the X DevAPI connector with compression support enabled using pip. ```bash pip install mysqlx-connector-python[compression] ``` -------------------------------- ### Install Connector/Python from Source Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/installation.md Install Connector/Python from source on Unix-like systems, specifying paths for Protobuf and protoc. Replace , , and with actual paths. ```bash python setup.py install --with-protobuf-include-dir= --with-protobuf-lib-dir= --with-protoc= ``` -------------------------------- ### Install MySQL Connector/Python with Telemetry Source: https://context7.com/mysql/mysql-connector-python/llms.txt Install the Classic API connector with telemetry support enabled using pip. ```bash pip install mysql-connector-python[telemetry] ``` -------------------------------- ### Install MySQL X DevAPI with Compression Source: https://github.com/mysql/mysql-connector-python/blob/trunk/README.rst Install the X DevAPI connector with optional compression functionality dependencies using pip. ```bash # 3rd party packages to unleash the compression functionality are installed $ pip install mysqlx-connector-python[compression] ``` -------------------------------- ### Display setup.py Help for Connector/Python Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/installation.md View all available options and commands for the setup.py script when installing Connector/Python from source. ```bash shell> python setup.py --help ``` -------------------------------- ### Tutorials - Indexes Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/index.md Guides on creating and managing indexes for collections. ```APIDOC ## Tutorials - Creating Indexes ### Arguments for `mysqlx.Collection.create_index()` #### Description Details the parameters required for the `create_index()` method. ### Using `mysqlx.Collection.create_index()` #### Description Provides examples and usage instructions for creating indexes on collections. ``` -------------------------------- ### Install MySQL Connector/Python with Telemetry Source: https://github.com/mysql/mysql-connector-python/blob/trunk/README.rst Install the Classic API connector with optional telemetry functionality dependencies using pip. ```bash # 3rd party packages to unleash the telemetry functionality are installed $ pip install mysql-connector-python[telemetry] ``` -------------------------------- ### Install MySQL Connector/Python (Classic API) Source: https://github.com/mysql/mysql-connector-python/blob/trunk/README.rst Use this command to install the Classic API connector for MySQL Connector/Python using pip. ```bash $ pip install mysql-connector-python ``` -------------------------------- ### Connect to MySQL Server and Get Schema Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/creating_indexes.md Establishes a connection to the MySQL server and retrieves a specific schema. Ensure you have the mysqlx library installed and valid connection credentials. ```python import mysqlx # Connect to server on localhost session = mysqlx.get_session({ 'host': 'localhost', 'port': 33060, 'user': 'mike', 'password': 's3cr3t!' }) schema = session.get_schema('test') ``` -------------------------------- ### Tutorials - Collections Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/index.md Guides on how to use collections for document storage and manipulation. ```APIDOC ## Tutorials - Collections ### Creating Collections #### Description Demonstrates how to create new collections within a schema. #### Schema Validation ##### Description Explains how to apply schema validation rules when creating collections. ### Modifying Collections #### Description Provides guidance on altering existing collections. ### Using Collection Patch (`mysqlx.ModifyStatement.patch()`) #### Description Illustrates how to use the `patch()` method for partial updates to documents within a collection. ``` -------------------------------- ### Install MySQL X DevAPI Connector Source: https://github.com/mysql/mysql-connector-python/blob/trunk/README.rst Use this command to install the X DevAPI connector for MySQL Connector/Python using pip. ```bash $ pip install mysqlx-connector-python ``` -------------------------------- ### Example Document Output Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/connection_pooling.md This is an example of the output format when fetching documents from a collection. It displays document IDs and associated names. ```python [{'_id': '00005b770c7f0000000000000389', 'name': 'Worker_2'}, {'_id': '00005b770c7f000000000000038a', 'name': 'Worker_2'}, {'_id': '00005b770c7f000000000000038b', 'name': 'Worker_2'}, {'_id': '00005b770c7f000000000000038c', 'name': 'Worker_2'}, {'_id': '00005b770c7f000000000000038d', 'name': 'Worker_2'}, {'_id': '00005b770c7f000000000000038e', 'name': 'Worker_2'}, {'_id': '00005b770c7f000000000000038f', 'name': 'Worker_2'}, {'_id': '00005b770c7f0000000000000390', 'name': 'Worker_2'}, {'_id': '00005b770c7f0000000000000391', 'name': 'Worker_2'}, {'_id': '00005b770c7f0000000000000392', 'name': 'Worker_2'}, {'_id': '00005b770c7f0000000000000393', 'name': 'Worker_1'}, {'_id': '00005b770c7f0000000000000394', 'name': 'Worker_4'}, {'_id': '00005b770c7f0000000000000395', 'name': 'Worker_1'}, {'_id': '00005b770c7f0000000000000396', 'name': 'Worker_4'}, {'_id': '00005b770c7f0000000000000397', 'name': 'Worker_7'}, {'_id': '00005b770c7f0000000000000398', 'name': 'Worker_1'}, {'_id': '00005b770c7f0000000000000399', 'name': 'Worker_4'}, {'_id': '00005b770c7f000000000000039a', 'name': 'Worker_7'}, {'_id': '00005b770c7f000000000000039b', 'name': 'Worker_1'}, {'_id': '00005b770c7f000000000000039c', 'name': 'Worker_4'}, {'_id': '00005b770c7f000000000000039d', 'name': 'Worker_7'}, {'_id': '00005b770c7f000000000000039e', 'name': 'Worker_1'}, {'_id': '00005b770c7f000000000000039f', 'name': 'Worker_8'}, {'_id': '00005b770c7f00000000000003a0', 'name': 'Worker_4'}, {'_id': '00005b770c7f00000000000003a1', 'name': 'Worker_7'}, ... {'_id': '00005b770c7f000000000000043c', 'name': 'Worker_9'}] ``` -------------------------------- ### Connect and Query with Classic API Source: https://github.com/mysql/mysql-connector-python/blob/trunk/README.rst Connects to a MySQL server using the Classic API, executes a query to get the current date, and fetches the result. Ensure you have the `mysql.connector` library installed. ```python 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() ``` -------------------------------- ### Install Connector/Python using RPM Package Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/installation.md Install Connector/Python on Linux using an RPM package. Replace PACKAGE.rpm with the actual filename. ```bash shell> rpm -i PACKAGE.rpm ``` -------------------------------- ### Tutorials - Locking Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/index.md Guides on implementing locking mechanisms for data concurrency control. ```APIDOC ## Tutorials - Locking ### Shared and Exclusive Locks #### Description Explains the concepts and usage of shared and exclusive locks. #### Examples ##### Description Illustrative examples of applying shared and exclusive locks. ### Locking with NOWAIT and SKIP_LOCKED #### Description Details how to use `NOWAIT` and `SKIP_LOCKED` options for lock management. ``` -------------------------------- ### Install coverage.py Package Source: https://github.com/mysql/mysql-connector-python/blob/trunk/CONTRIBUTING.md Install the coverage.py package using pip. This is a prerequisite for generating test coverage reports. ```bash python -m pip install coverage ``` -------------------------------- ### Setup Initial Data Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/locking.md Assumes the existence of a collection named 'test_collection' within 'test_schema'. This snippet defines the initial data structure. ```python [ { "_id": "1", "name": "Fred", "age": 21 },{ "_id": "2", "name": "Sakila", "age": 23 },{ "_id": "3", "name": "Mike", "age": 42 } ] ``` -------------------------------- ### Install Connector/Python using Yum Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/installation.md Install Connector/Python on Linux systems that use the Yum package manager after updating the repository. ```bash shell> sudo yum install mysqlx-connector-python ``` -------------------------------- ### Install Connector/Python using Debian Package Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/installation.md Install Connector/Python on Linux using a Debian package. Replace PACKAGE.deb with the actual filename. ```bash shell> dpkg -i PACKAGE.deb ``` -------------------------------- ### Tutorials - Transactions Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/index.md Guides on managing database transactions, including savepoints. ```APIDOC ## Tutorials - Transactions ### Savepoints #### Description Covers the use of savepoints for managing transaction states. ##### Get the Collection Object ###### Description How to obtain a collection object to perform transaction operations. ##### Set and Rollback to a Named Transaction Savepoint ###### Description Steps for setting and rolling back to a named savepoint. ##### Set and Rollback to an Unnamed Transaction Savepoint ###### Description Steps for setting and rolling back to an unnamed savepoint. ##### Releasing a Transaction Savepoint ###### Description How to release a transaction savepoint. ``` -------------------------------- ### MySQL X DevAPI Client Options Dictionary Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/mysqlx.get_client.md Example of a dictionary for configuring client options, including pooling settings and timeouts. This can be passed to the mysqlx.get_client function. ```python options = { 'pooling': { 'enabled': (bool), # [True | False], True by default 'max_size': (int), # Maximum connections per pool "max_idle_time": (int), # milliseconds that a # connection will remain active while not in use. # By default 0, means infinite. "queue_timeout": (int), # milliseconds a request will # wait for a connection to become available. # By default 0, means infinite. } } ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/mysql/mysql-connector-python/blob/trunk/CONTRIBUTING.md Install the pre-commit package and its git hooks to automatically check code quality before committing. This helps identify issues early in the development process. ```bash shell> python -m pip install pre-commit shell> pre-commit install ``` -------------------------------- ### MySQL X DevAPI Connection String URI Format Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/mysqlx.get_client.md Example of a connection string URI for establishing a connection to a MySQL server. Ensure to replace placeholders with your actual credentials and host information. ```python cnx_str = 'mysqlx://{user}:{pwd}@{host}:{port}' ``` ```python cnx_str = ('mysqlx://{user}:{pwd}@[ (address={host}:{port}, priority=n), (address={host}:{port}, priority=n), ...] ?[option=value]') ``` -------------------------------- ### Multi-host Failover with Connection Pooling Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/connection_routers.md Demonstrates multi-host failover using connection pooling. This example configures a primary host that is unreachable and a secondary host. The connector attempts the primary host first, and if it fails, it connects to the secondary host. An error is raised if the pool reaches its `max_size` and another session is requested. ```python import mysqlx routers = [{"host": "unreachable_host", "priority": 100}, {"host": "127.0.0.1", "port": 33060, "priority": 90} ] connection_dict = { 'routers': routers, 'port': 33060, 'user': 'mike', 'password': 's3cr3t!', 'connect_timeout': 2000 } options_dict = {'pooling':{'max_size': 5, 'queue_timeout': 1000}} client = mysqlx.get_client(connection_dict, options_dict) for n in range(5): print(f"session: {n}") session = client.get_session() res = session.sql("select connection_id()").execute().fetch_all() for row in res: print(f"connection id: {row[0]}") # Since the "unreachable_host" is unavailable and the max_size option for # the pools is set to 5, we can only get 5 sessions prior to get an error. # By requiring another session a mysqlx.errors.PoolError error is raised. client.get_session() # This line raises an PoolError ``` -------------------------------- ### Perform Regression with MySQL Connector/Python Source: https://context7.com/mysql/mysql-connector-python/llms.txt Example of fitting a regressor and generating predictions using a database connection. ```python with connector.connect(user='root', database='mlcorpus') as db_connection: X = pd.DataFrame({"x1": [1, 2, 3, 4, 5], "x2": [2, 4, 6, 8, 10]}) y = pd.Series([2.5, 5.0, 7.5, 10.0, 12.5]) regressor = MyRegressor(db_connection) regressor.fit(X, y) predictions = regressor.predict(X) print(f"Regression predictions: {predictions}") ``` -------------------------------- ### Get Session and Collection Objects Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/locking.md Establishes connections and retrieves schema and collection objects for two separate clients. Ensure the connection details are correct for your environment. ```python # client 1 session_1 = mysqlx.get_session("root:@localhost:33060") schema_1 = session_1.get_schema("test_schema") collection_1 = schema_1.get_collection("test_collection") # client 2 session_2 = mysqlx.get_session("root:@localhost:33060") schema_2 = session_2.get_schema("test_schema") collection_2 = schema_2.get_collection("test_collection") ``` -------------------------------- ### MySQL X DevAPI Connection Dictionary Format Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/mysqlx.get_client.md Example of a dictionary structure for providing connection details to the MySQL X DevAPI client. This format is an alternative to using a connection string URI. ```python cnx_dict = { 'host': 'The host where the MySQL product is running', 'port': '(int) the port number configured for X protocol', 'user': 'The user name account', 'password': 'The password for the given user account', 'ssl-mode': 'The flags for ssl mode in mysqlx.SSLMode.FLAG', 'ssl-ca': 'The path to the ca.cert', "connect-timeout": '(int) milliseconds to wait on timeout' } ``` -------------------------------- ### Shared Lock Example Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/locking.md Demonstrates acquiring shared locks on different documents by two clients. Client 2 can acquire a shared lock on document '1' immediately after Client 1, as shared locks do not block each other. ```python # client 1 session_1.start_transaction() collection_1.find("_id = '1'").lock_shared().execute() # client 2 session_2.start_transaction() collection_2.find("_id = '2'").lock_shared().execute() # should return immediately collection_2.find("_id = '1'").lock_shared().execute() # should return immediately # client 1 session_1.rollback() # client 2 session_2.rollback() ``` -------------------------------- ### Initialize Client with Connection Dictionary Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/connection_pooling.md Alternatively, use a dictionary for connection settings with `mysqlx.get_client()`. This method also requires closing the client and session when finished. ```python import mysqlx connection_dict = { 'host': 'localhost', 'port': 33060, 'user': 'mike', 'password': 's3cr3t!' } options_dict = {} client = mysqlx.get_client(connection_dict, options_dict) session = client.get_session() # (...) session.close() client.close() ``` -------------------------------- ### Initialize Client with Connection String Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/connection_pooling.md Use `mysqlx.get_client()` with a connection string to establish a client connection for connection pooling. Ensure the client and session are closed when no longer needed. ```python import mysqlx connection_str = 'mysqlx://mike:s3cr3t!@localhost:33060' options_string = '{}' # An empty document client = mysqlx.get_client(connection_str, options_string) session = client.get_session() # (...) session.close() client.close() ``` -------------------------------- ### mysqlx.Client Initialization and Methods Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/mysqlx.Client.md This snippet covers the initialization of the mysqlx.Client class and its primary methods for managing sessions and connections. ```APIDOC ## mysqlx.Client Class ### Description Class defining a client, it stores a connection configuration. ### Parameters #### Constructor Parameters - **connection_dict** (dict) - Required - The connection information to connect to a MySQL server. - **options_dict** (dict) - Optional - The options to configure this client. ### Methods #### close() Closes the sessions opened by this client. - **Returns:** None #### get_session() Creates a Session instance using the provided connection data. - **Returns:** Session object. - **Return type:** [Session](mysqlx.Session.md#mysqlx.Session) ``` -------------------------------- ### Run Full Test Suite with C-EXT Enabled on Linux Source: https://github.com/mysql/mysql-connector-python/blob/trunk/CONTRIBUTING.md Execute the entire test suite with C-EXT enabled from a Linux host, specifying MySQL user, password, and port. Assumes classic protocol. ```bash $ MYSQL_CEXT='true' MYSQL_PORT='3308' MYSQL_USER='docker' MYSQL_PASSWORD='s3cr3t' ./tests/docker/runner.sh ``` -------------------------------- ### MySQL Connection using Context Manager (Classic API) Source: https://context7.com/mysql/mysql-connector-python/llms.txt Demonstrates using a context manager for automatic connection and cursor cleanup. This is a recommended practice for resource management. ```python import mysql.connector config = { "host": "localhost", "port": 3306, "database": "test", "user": "root", "password": "secret", "charset": "utf8", "use_unicode": True, "get_warnings": True, } # Using context manager for automatic cleanup with mysql.connector.connect(**config) as cnx: with cnx.cursor() as cursor: cursor.execute("SELECT * FROM users WHERE id = %s", (1,)) user = cursor.fetchone() print(user) # Connection automatically closed when exiting context ``` -------------------------------- ### Connection Pooling with X DevAPI Client Source: https://context7.com/mysql/mysql-connector-python/llms.txt Shows how to create a client with connection pooling enabled and manage sessions. Ensure the client configuration includes pooling details. ```python import mysqlx # Create a client with connection pooling client = mysqlx.get_client({ "host": "127.0.0.1", "port": 33060, "user": "root", "password": "secret" }, { "pooling": { "enabled": True, "max_size": 10, "max_idle_time": 30000, # milliseconds "queue_timeout": 10000 # milliseconds } }) # Get session from pool session = client.get_session() schema = session.get_schema("test_db") collection = schema.get_collection("users") # Perform operations result = collection.find().limit(5).execute() for doc in result.fetch_all(): print(doc) # Close session (returns to pool) session.close() # Get another session from pool session2 = client.get_session() # ... do work ... session2.close() # Close client and all pooled connections client.close() ``` -------------------------------- ### count Property Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/mysqlx.BufferingResult.md Gets the total number of items in the result. ```APIDOC ## Property count ### Description The total of items. ### Type int ``` -------------------------------- ### Run the Entire Test Suite Source: https://github.com/mysql/mysql-connector-python/blob/trunk/CONTRIBUTING.md Execute the complete test suite for mysqlx-connector-python. Requires specifying MySQL and Protobuf directories if the C extension is enabled. ```bash shell> python unittests.py --with-mysql= --with-protobuf-include-dir= --with-protobuf-lib-dir= --with-protoc= ``` ```bash shell> python unittests.py --with-mysql=/usr/local/mysql --with-protobuf-include-dir=/usr/local/protobuf/include --with-protobuf-lib-dir=/usr/local/protobuf/lib --with-protoc=/usr/local/protobuf/bin/protoc ``` -------------------------------- ### Run Full Test Suite on Linux Source: https://github.com/mysql/mysql-connector-python/blob/trunk/CONTRIBUTING.md Execute the entire test suite from a Linux host with specified MySQL user, password, and port. Assumes classic protocol. ```bash $ MYSQL_PORT='3308' MYSQL_USER='docker' MYSQL_PASSWORD='s3cr3t' ./tests/docker/runner.sh ``` -------------------------------- ### Get Document by ID Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/mysqlx.Collection.md Retrieves a single document from the collection that matches the provided document ID. ```python collection.get_one(doc_id='doc1') ``` -------------------------------- ### mysqlx.get_client Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/mysqlx.get_client.md Creates a Client instance with the provided connection data and settings. ```APIDOC ## mysqlx.get_client ### Description Creates a Client instance with the provided connection data and settings. ### Method `mysqlx.get_client` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **connection_string** (str | Dict[str, Any]) - Required - A string or a dict type object to indicate the connection data used to connect to a MySQL server. * String URI format: ```default cnx_str = 'mysqlx://{user}:{pwd}@{host}:{port}' cnx_str = ('mysqlx://{user}:{pwd}@[ ' (address={host}:{port}, priority=n), ' (address={host}:{port}, priority=n), ...] ' ?[option=value]') ``` * Dictionary format: ```default cnx_dict = { 'host': 'The host where the MySQL product is running', 'port': '(int) the port number configured for X protocol', 'user': 'The user name account', 'password': 'The password for the given user account', 'ssl-mode': 'The flags for ssl mode in mysqlx.SSLMode.FLAG', 'ssl-ca': 'The path to the ca.cert', "connect-timeout": '(int) milliseconds to wait on timeout' } ``` * **options_string** (str | Dict[str, Any]) - Required - A string in the form of a document or a dictionary type with configuration for the client. * Options format: ```default options = { 'pooling': { 'enabled': (bool), # [True | False], True by default 'max_size': (int), # Maximum connections per pool "max_idle_time": (int), # milliseconds that a connection will remain active while not in use. By default 0, means infinite. "queue_timeout": (int) # milliseconds a request will wait for a connection to become available. By default 0, means infinite. } } ``` ### Request Example ```python # Example using connection string from mysqlx import get_client connection_string = "mysqlx://user:password@host:port" client = get_client(connection_string) # Example using dictionary connection_dict = { 'host': 'localhost', 'port': 33060, 'user': 'root', 'password': 'password' } client = get_client(connection_dict) # Example with options options_dict = { 'pooling': { 'enabled': True, 'max_size': 10 } } client = get_client(connection_string, options_dict) ``` ### Response #### Success Response (200) * **Client** (mysqlx.Client) - The created Client object. #### Response Example ```python # Assuming 'client' is the returned Client object print(client) ``` #### Versionadded Added in version 8.0.13. ``` -------------------------------- ### Create and Get Collection Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/creating_indexes.md Creates a new collection within the specified schema if it does not already exist, and then retrieves a reference to it. ```python # Create 'collection_GOT' in schema schema.create_collection('collection_GOT') # Get 'collection_GOT' from schema collection = schema.get_collection('collection_GOT') ``` -------------------------------- ### Create Sample Collection Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/collections.md Create a sample collection named 'collection_GOT' within a specified schema. This is often a preparatory step before adding data or performing other operations. ```python # Create 'collection_GOT' in schema schema.create_collection('collection_GOT') ``` -------------------------------- ### Connect to MySQL and Create Collection Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/getting_started.md Connects to a MySQL server and creates a new collection within a specified schema. Requires the 'mysqlx' library. ```python # Connecting to MySQL and working with a Session import mysqlx # Connect to a dedicated MySQL server session = mysqlx.get_session({ 'host': 'localhost', 'port': 33060, 'user': 'mike', 'password': 's3cr3t!' }) schema = session.get_schema('test') # Create 'my_collection' in schema schema.create_collection('my_collection') # Get 'my_collection' from schema collection = schema.get_collection('my_collection') ``` -------------------------------- ### Update MySQL Yum Repository Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/installation.md Before installing Connector/Python using Yum on Linux, ensure your MySQL Yum repository is up-to-date. ```bash shell> sudo yum update mysql-community-release ``` -------------------------------- ### Get Schema Object Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/getting_started.md Retrieves a Schema object for a given database name. This can be done by chaining calls after establishing a session. ```python schema = mysqlx.get_session().get_schema('test') ``` ```python session = mysqlx.get_session() schema = session.get_schema('test') ``` -------------------------------- ### Run C-EXT Tests with Pattern Source: https://github.com/mysql/mysql-connector-python/blob/trunk/CONTRIBUTING.md Execute C-EXT related tests matching the 'cext' pattern. Requires enabling C-EXT build and setting MYSQL_PASSWORD. ```bash $ MYSQL_CEXT='true' TEST_PATTERN='cext.*' MYSQL_PASSWORD='s3cr3t' ./tests/docker/runner.sh ``` -------------------------------- ### Transaction Management Methods Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/mysqlx.Session.md Methods for controlling database transactions, including starting, committing, rolling back, and managing savepoints. ```APIDOC ## Transaction Management ### commit() → None Commits all the operations executed after a call to startTransaction(). ### rollback() → None Discards all the operations executed after a call to startTransaction(). ### rollback_to(name: str) → None Rollback to a transaction savepoint with the given name. * **Parameters**: **name** (string) – The savepoint name. ### set_savepoint(name: str | None = None) → str Creates a transaction savepoint. If a name is not provided, one will be generated using the uuid.uuid1() function. * **Parameters**: **name** (Optional [string]) – The savepoint name. * **Returns**: The savepoint name. * **Return type**: string ### start_transaction() → None Starts a transaction context on the server. ### release_savepoint(name: str) → None Release a transaction savepoint with the given name. * **Parameters**: **name** (string) – The savepoint name. ``` -------------------------------- ### Connect and Query with X DevAPI Source: https://github.com/mysql/mysql-connector-python/blob/trunk/README.rst Connects to a MySQL server using the X DevAPI, retrieves a document from a collection, and prints a specific field. Requires `mysqlx` library. ```python import mysqlx # Connect to server session = mysqlx.get_session( host="127.0.0.1", port=33060, user="mike", password="s3cr3t!") schema = session.get_schema("test") # Use the collection "my_collection" collection = schema.get_collection("my_collection") # Specify which document to find with Collection.find() result = collection.find("name like :param") \ .bind("param", "S%") \ .limit(1) \ .execute() # Print document docs = result.fetch_all() print(r"Name: {0}".format(docs[0]["name"])) # Close session session.close() ``` -------------------------------- ### Get MySQL Collection Object Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/transactions.md Establishes a connection to the MySQL server and retrieves a specific schema and collection object. Ensure the MySQL server is running and accessible. ```python session = mysqlx.get_session("root:@localhost:33060") schema = session.get_schema("test_schema") collection = schema.get_collection("test_collection") ``` -------------------------------- ### Run Entire Test Suite Source: https://github.com/mysql/mysql-connector-python/blob/trunk/CONTRIBUTING.md Execute the complete test suite for mysql-connector-python. The `--with-mysql` and `--with-mysql-capi` flags are necessary when the C extension is enabled. ```bash shell> python unittests.py --with-mysql= --with-mysql-capi= ``` ```bash shell> python unittests.py --with-mysql=/usr/local/mysql --with-mysql-capi=/usr/local/mysql ``` -------------------------------- ### Exclusive Lock Example Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/locking.md Illustrates exclusive locking where Client 2's attempt to acquire an exclusive lock on document '1' will block until Client 1 releases its lock. ```python # client 1 session_1.start_transaction() collection_1.find("_id = '1'").lock_exclusive().execute() # client 2 session_2.start_transaction() collection_2.find("_id = '2'").lock_exclusive().execute() # should return immediately collection_2.find("_id = '1'").lock_exclusive().execute() # session_2 should block # client 1 session_1.rollback() # session_2 should unblock now # client 2 session_2.rollback() ``` -------------------------------- ### Connect with Multiple Hosts via `routers` Option (With Priority) Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/connection_routers.md Configure multiple hosts with priorities using a list of dictionaries for the `routers` option. The `connect_timeout` option is recommended when a large number of hosts could be down. ```python import mysqlx routers = [{"host": "unreachable_host", "priority": 100}, # default port is 33060 {"host": "127.0.0.1", "port": 33060, "priority": 90} ] connection_dict = { 'routers': routers, 'port': 33060, 'user': 'mike', 'password': 's3cr3t!', 'connect_timeout': 2000 } options_dict = {} client = mysqlx.get_client(connection_dict, options_dict) session = client.get_session() # (...) session.close() client.close() ``` -------------------------------- ### Connect with User-Specified Connection Attributes via URL Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/connection_attributes.md Establish a MySQL connection using a URL, including user-specified connection attributes like 'my_attribute' and 'foo'. User-defined attributes cannot start with an underscore. ```python import mysqlx mysqlx.getSession('mysqlx://mike@localhost:33060/schema?connection-attributes=[my_attribute=some_value,foo=bar]') ``` -------------------------------- ### Configure Connection Pooling with Routers Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/connection_routers.md Use this snippet to establish connections to multiple MySQL hosts with defined priorities and configure connection pooling. Ensure `mysqlx` is imported. The `connection_dict` defines the routers and connection parameters, while `options_dict` specifies pooling settings like `max_size` and `queue_timeout`. ```python import mysqlx routers = [{"host": "localhost", "priority": 100}, # default port is 33060 {"host": "127.0.0.1", "port": 33060, "priority": 90} ] connection_dict = { 'routers': routers, 'port': 33060, 'user': 'root', 'password': '', 'connect_timeout':2000 } options_dict = {'pooling':{'max_size': 5, 'queue_timeout': 1000}} client = mysqlx.get_client(connection_dict, options_dict) # We can get 5 sessions from each pool. for n in range(5): print(f"session: {n}") session = client.get_session() res = session.sql("select connection_id()").execute().fetch_all() for row in res: print(f"connection id: {row[0]}") for n in range(5): print(f"session: {n}") session = client.get_session() res = session.sql("select connection_id()").execute().fetch_all() for row in res: print(f"connection id: {row[0]}") ``` -------------------------------- ### Connect with Multiple Hosts via `routers` Option (No Priority) Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/connection_routers.md Configure multiple hosts by providing a list of dictionaries to the `routers` option in connection settings. The same MySQL user and password must exist on all endpoints. ```python import mysqlx routers = [ {"host": "unreachable_host"}, # default port is 33060 {"host": "127.0.0.1", "port": 33060}, ] connection_dict = { 'routers': routers, 'port': 33060, 'user': 'mike', 'password': 's3cr3t!' 'connect_timeout': 2000, } options_dict = {} # empty dict object client = mysqlx.get_client(connection_dict, options_dict) session = client.get_session() # (...) session.close() client.close() ``` -------------------------------- ### MySQL Connector/Python Error Handling Example Source: https://context7.com/mysql/mysql-connector-python/llms.txt Demonstrates comprehensive error handling for various MySQL-specific exceptions, including connection, integrity, programming, and operational errors. Ensures proper rollback and connection closing. ```python import mysql.connector from mysql.connector import Error, InterfaceError, DatabaseError from mysql.connector import ProgrammingError, IntegrityError, OperationalError try: cnx = mysql.connector.connect( host="localhost", user="root", password="secret", database="test" ) cursor = cnx.cursor() # This might raise IntegrityError on duplicate key cursor.execute("INSERT INTO users (id, name) VALUES (1, 'Test')") cnx.commit() except InterfaceError as e: print(f"Interface error (connection issue): {e}") except IntegrityError as e: print(f"Integrity error (constraint violation): {e}") cnx.rollback() except ProgrammingError as e: print(f"Programming error (SQL syntax): {e}") except OperationalError as e: print(f"Operational error (server issue): {e}") except DatabaseError as e: print(f"Database error: {e}") except Error as e: print(f"MySQL error: {e}") finally: if 'cnx' in locals() and cnx.is_connected(): cursor.close() cnx.close() ``` -------------------------------- ### Acquire Row Lock Without Waiting (SKIP_LOCKED) Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/locking.md Use SKIP_LOCKED to acquire a row lock immediately. If the row is locked, it is removed from the result set instead of waiting. This example shows two clients interacting with shared and exclusive locks. ```python # client 1 session_1.start_transaction() collection_1.find("_id = :id").lock_shared().bind("id", "1").execute() # client 2 session_2.start_transaction() collection_2.find("_id = :id").lock_exclusive(mysqlx.LockContention.SKIP_LOCKED) \ .bind("id", "1").execute() # The execution should return immediately, no error is thrown # client 1 session_1.commit() # client 2 collection_2.find("_id = :id").lock_exclusive(mysqlx.LockContention.SKIP_LOCKED) \ .bind("id", 1).execute() # Since commit is done in 'client 1' then the read must be possible now and # no error is thrown session_2.rollback() ``` -------------------------------- ### Connect to MySQL with Default Schema Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/getting_started.md Establishes a session with MySQL, specifying a default schema. The default schema must exist on the server. ```python session = mysqlx.get_session({ 'host': 'localhost', 'port': 33060, 'user': 'root', 'password': '', 'schema': 'my_schema' }) ``` -------------------------------- ### Create Spatial Index with GEOJSON and Mixed Field Types Source: https://github.com/mysql/mysql-connector-python/blob/trunk/mysqlx-connector-python/docs/mysqlx/tutorials/creating_indexes.md Creates a spatial index named 'index_age' using GEOJSON data for '$.geoField' and other types for '$.intField', '$.floatField', and '$.dateField'. The index type is set to 'SPATIAL', and specific options like 'options' and 'srid' are provided for the GEOJSON field. Note: The example code has a duplicate index name 'index_age' which might be an error in the source. ```python collection.create_index("index_age", {"fields": [{"field": "$.geoField", "type": "GEOJSON", "required": False, "options": 2, "srid": 4326}, {"field": "$.intField", "type": "INT", "required": True}, {"field": "$.floatField", "type": "FLOAT", "required": True}, {"field": "$.dateField", "type": "DATE", "required": True}], "type" : "SPATIAL"}) ``` -------------------------------- ### Run Tests with C-Extension Enabled Source: https://github.com/mysql/mysql-connector-python/blob/trunk/CONTRIBUTING.md To build and run tests with the `mysqlx` C-extension enabled, set the `MYSQLX_CEXT` environment variable to 'true'. Use `TEST_PATTERN` to specify tests and `MYSQL_PASSWORD` for authentication. ```bash $ MYSQLX_CEXT='true' TEST_PATTERN='mysqlx_crud' MYSQL_PASSWORD='s3cr3t' ./tests/docker/runner.sh ``` -------------------------------- ### Basic MySQL Connection (Classic API) Source: https://context7.com/mysql/mysql-connector-python/llms.txt Establishes a basic connection to a MySQL server using the Classic API and executes a simple query. Ensure you have the necessary connection details. ```python import mysql.connector # Basic connection cnx = mysql.connector.connect( host="127.0.0.1", port=3306, user="root", password="secret", database="mydb" ) # Get a cursor and execute queries cursor = cnx.cursor() cursor.execute("SELECT CURDATE()") row = cursor.fetchone() print(f"Current date is: {row[0]}") # Close connection cursor.close() cnx.close() ```