Python mysql connect port

Connecting to MySQL using Connector/Python

To connect to the database we use the connect() function of the mysql.connector module. It accepts connection credentials and returns an object of type MySQLConnection or CMySQLConnection (if C extension is installed).

The following table lists some common arguments of the connect() function.

Argument Default Description
database Database name
user Username to authenticate to authenticate with MySQL
password Password to authenticate the user
host 127.0.0.1 Hostname where the MySQL server is installed
port 3306 The TCP/IP port of the MySQL server

Note: For complete list of arguments consult the official documentation.

The code in the following listing connects to the world database and prints the connection id.

1 2 3 4 5 6 7 8 9 10 11 12
import mysql.connector db = mysql.connector.connect( host='localhost', database='world', user='root', password='pass' ) print("Connection ID:", db.connection_id) print(db) 

Expected Output:

Since I am on a Linux distribution where C extension is installed, the connect() function returns an object of type CMySQLConnection instead of MySQLConnection .

On a system where the C extension is not installed the output will look like this:

Instead of passing connection credentials as keyword arguments, you also pass them in a dictionary.

1 2 3 4 5 6 7 8 9 10 11 12 13 14
import mysql.connector connection_args =  'host': 'localhost', 'database': 'world', 'user': 'root', 'password': 'pass' > db = mysql.connector.connect(**connection_args) print("Connection ID:", db.connection_id) print(db) 

Using pure Python or C Extension #

The use_pure connection argument determines whether to use C extension or not. If use_pure set to True , Connector/Python will use the pure Python implementation. As of 8.0.11, the
use_pure argument defaults to False . This is the reason why preceding snippet uses the C extension. If however, use_pure is set to False and the C extension is not available, then Connector/Python will use the pure Python implementation.

1 2 3 4 5 6 7 8 9 10 11 12 13
import mysql.connector db = mysql.connector.connect( host='localhost', database='world', user='root', password='pass', use_pure=True # use pure Python implementation ) print("Connection ID:", db.connection_id) print(db) 

Expected Output:

Closing Connection #

The connection to the database is automatically closed when the program ends. However, it is always good idea to close the connection explicitly when you are finished working with it.

To close the connection, we use the close() method of the MySQLConnection object.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
import mysql.connector db = mysql.connector.connect( host='localhost', database='world', user='root', password='pass', use_pure=True ) print("Connection ID:", db.connection_id) print(db) db.close() # close the connection 

We now know how to connect to the database. Let’s see how we can handle errors.

Using Configuration Files #

Hardcoding connection credentials into the application is fine for testing purposes but it is not very feasible for the production environment for two good reasons.

  1. Anyone who has access to the source can peek into the connection details.
  2. On migrating to a new server, you would have to update the source code again.

A much better approach is to store the connection details in an external file. Since version 2.0 Connector/Python can read connection details from a Windows-INI-style file.

The following two arguments control settings about the configuration files:

Argument Default Description
option_files It species the configuration files to read. Its value can be a string or list of strings.
option_groups [‘client’, ‘connector_python’] It specifies the name of the section to read options from. By default, options are only read from client and connector_python section.

Create a new file named my.conf with the connection credentials as follows:

[connector_python] host = 127.0.0.1 database = world user = root password = pass port = 3306 

The code in the following listing reads connection details from my.conf file.

import mysql.connector db = mysql.connector.connect(option_files='my.conf') print("Connection ID:", db.connection_id) print(db) db.close() 

Notice that in my.conf file we have specified the connection details under the section connector_python’ , which is one of the two sections from where MySQL Connector/Python will read options by default. If you want to change section name use the option_groups argument, as follows:

[connection_details] host = 127.0.0.1 database = blog user = root password = pass port = 3306 
import mysql.connector db = mysql.connector.connect(option_files='my.conf', option_groups=['connection_details']) print("Connection ID:", db.connection_id) print(db) db.close() 

We can also split the connection details into multiple files. This can come in handy when you want to share some configuration across connections.

[connector_python] host = 127.0.0.1 port = 3306 
[connector_python] database = world user = root password = pass 

To read options from multiple configuration files change the value of option_files to a list.

import mysql.connector db = mysql.connector.connect(option_files=['my1.conf', 'my1.conf']) print("Connection ID:", db.connection_id) print(db) db.close() 

MySQL Connector/Python Tutorial

  • Intro to MySQL Connector/Python
  • Installing MySQL Connector Python
  • Connecting to MySQL using Connector/Python
  • Executing Queries using Connector/Python
  • Exception Handling in Connector/Python
  • Creating Tables using Connector/Python
  • Inserting Data using Connector/Python
  • Updating Data using Connector/Python
  • Deleting Data using Connector/Python
  • Calling Stored Procedures using Connector/Python
  • Handling Transactions with Connector/Python
  • Connection Pooling using Connector/Python
  • Using Connector/Python C Extension

Recent Posts

  • Machine Learning Experts You Should Be Following Online
  • 4 Ways to Prepare for the AP Computer Science A Exam
  • Finance Assignment Online Help for the Busy and Tired Students: Get Help from Experts
  • Top 9 Machine Learning Algorithms for Data Scientists
  • Data Science Learning Path or Steps to become a data scientist Final
  • Enable Edit Button in Shutter In Linux Mint 19 and Ubuntu 18.04
  • Python 3 time module
  • Pygments Tutorial
  • How to use Virtualenv?
  • Installing MySQL (Windows, Linux and Mac)
  • What is if __name__ == ‘__main__’ in Python ?
  • Installing GoAccess (A Real-time web log analyzer)
  • Installing Isso

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

MySQL Connector/Python is implementing the MySQL Client/Server protocol completely in Python. No MySQL libraries are needed, and no compilation is necessary to run this Python DB API v2.0 compliant driver. Documentation & Download: http://dev.mysql.com/doc/connector-python/en

License

mysql/mysql-connector-python

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

…penTelemetry lib license info

Git stats

Files

Failed to load latest commit information.

README.rst

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). It also contains an implementation of the X DevAPI, an Application Programming Interface for working with the MySQL Document Store.

The recommended way to install Connector/Python is via pip.

Make sure you have a 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.

shell> pip install mysql-connector-python

Please refer to the installation tutorial for installation alternatives.

Using the MySQL classic protocol:

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: ".format(row[0])) # Close connection cnx.close()
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: ".format(docs[0]["name"])) # Close session session.close()
  • MySQL Connector/Python Developer Guide
  • MySQL Connector/Python X DevAPI Reference
  • MySQL Connector/Python Forum
  • MySQL Public Bug Tracker
  • Slack (Sign-up required if you do not have an Oracle account)
  • Stack Overflow
  • InsideMySQL.com Connectors Blog

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

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

Источник

Читайте также:  Поддержка https в php
Оцените статью