"mysql.connector" Module by mysql.com

Q

How to use "mysql.connector" module produced by mysql.com?

✍: FYIcenter.com

A

"mysql.connector" is the official Python module provided by mysql.com for MySQL database connection. You can follow this tutorial to try it.

1. Install "mysql-connector-python" package that contains the "mysql.connector" module. Do not use the outdated "mysql-connector" package.

fyicenter> pip3 install mysql-connector-python

...
Successfully installed mysql-connector-python-8.0.23 protobuf-3.15.6

2. Start a Python 3 interactive session and import the "mysql.connector" module.

fyicenter> python3 
Python 3.8.0 (v3.8.0:fa919fdf25) 

>>> import mysql.connector

>>> mysql.connector.1.03
'8.0.23'

3. Call the connect() method to establish a connection to a MySQL server with given accessing information. It returns a MySQLConnection object representing the established connection.

>>> con = mysql.connector.connect(host="127.0.0.1", port=3306,
...     user="guest", password="retneciyf")

>>> print(con)
<mysql.connector.connection.MySQLConnection object at 0x10701b640>

4. Use MySQLConnection methods and properties to see the MySQL environment.

>>> con.get_server_info()
'8.0.17'

>>> con.cmd_statistics()
{'Uptime': 1726469, 'Threads': 4, 'Questions': 64496, 'Slow queries': 0,
   ...

>>> con.user
'guest'

>>> con.charset
'utf8mb4'

5. Call cmd_init_db() method to set the default database to a database instance that your user name is allowed to use.

>>> con.cmd_init_db("test")
{'field_count': 0, 'affected_rows': 0, 'insert_id': 0, ...

>>> con.database
'test'

6. Run SQL statements on the connection as shown in next tutorials.

7. Close the connection at the end.

>>> con.is_connected() 
True 

>>> con.close()

>>> con.is_connected() 
False 

 

Change Data with "mysql.connector"

MySQL Database Server Connection Information

Python Modules for MySQL Database

⇑⇑ Python Tutorials

2021-11-13, 376👍, 0💬