The Wayback Machine - https://web.archive.org/web/20241128000816/https://www.geeksforgeeks.org/connect-mysql-database-using-mysql-connector-python/
Open In App

Connect MySQL database using MySQL-Connector Python

Last Updated : 18 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

While working with Python we need to work with databases, they may be of different types like MySQL, SQLite, NoSQL, etc. In this article, we will be looking forward to how to connect MySQL databases using MySQL Connector/Python.
MySQL Connector module of Python is used to connect MySQL databases with the Python programs, it does that using the Python Database API Specification v2.0 (PEP 249). It uses the Python standard library and has no dependencies.
 

Connecting to the Database

The mysql.connector provides the connect() method used to create a connection between the MySQL database and the Python application. The syntax is given below.

Syntax:

Conn_obj= mysql.connector.connect(host = <hostname>, user = <username>, passwd = <password>)    

The connect() function accepts the following arguments.

Hostname – It represents the server name or IP address on which MySQL is running.
Username – It represents the name of the user that we use to work with the MySQL server. By default, the username for the MySQL database is root.
Password – The password is provided at the time of installing the MySQL database. We don’t need to pass a password if we are using the root.
Database – It specifies the database name which we want to connect. This argument is used when we have multiple databases.
 

In the following example we will be connecting to MySQL database using connect()
Example:
 

Python3




# Python program to connect
# to mysql database
 
 
import mysql.connector
 
 
# Connecting from the server
conn = mysql.connector.connect(user = 'username',
                               host = 'localhost',
                              database = 'database_name')
 
print(conn)
 
# Disconnecting from the server
conn.close()


Output:
 

python-mysql-connect-1

Also for the same, we can use connection.MySQLConnection() class instead of connect():
Example:
 

Python3




# Python program to connect
# to mysql database
 
 
from mysql.connector import connection
 
# Connecting to the server
conn = connection.MySQLConnection(user = 'username',
                              host = 'localhost',
                              database = 'database_name')
 
print(conn)
 
# Disconnecting from the server
conn.close()


Output:
 

python-mysql-connect-2

Another way is to pass the dictionary in the connect() function using ‘**’ operator:
Example:
 

Python3




# Python program to connect
# to mysql database
 
 
from mysql.connector import connection
 
 
dict = {
  'user': 'root',
  'host': 'localhost',
  'database': 'College'
}
 
# Connecting to the server
conn = connection.MySQLConnection(**dict)
 
print(conn)
 
# Disconnecting from the server
conn.close()


Output:
 

python-mysql-connect-3

 Example

Python3




# importing required libraries
import mysql.connector
 
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="gfg"
)
 
# preparing a cursor object
cursorObject = dataBase.cursor()
 
# creating database
cursorObject.execute("CREATE DATABASE geeks4geeks")



Image

 



Previous Article
Next Article

Similar Reads

Extract Data from Database using MySQL-Connector and XAMPP in Python
Prerequisites: MySQL-Connector, XAMPP Installation A connector is employed when we have to use MySQL with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. RequirementsXAMPP: Database / Server
2 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
How to install MySQL connector package in Python?
Prerequisite: Python Language Introduction MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. A connector is employed when we have to use MySQL with other programmin
2 min read
How to connect to SQLite database that resides in the memory using Python ?
In this article, we will learn how to Connect an SQLite database connection to a database that resides in the memory using Python. But first let brief about what is sqlite. SQLite is a lightweight database software library that provides a relational database management system. Generally, it is a server-less database that can be used within almost a
3 min read
PostgreSQL - Connect To PostgreSQL Database Server in Python
The psycopg database adapter is used to connect with PostgreSQL database server through python. Installing psycopg: First, use the following command line from the terminal: pip install psycopg If you have downloaded the source package into your computer, you can use the setup.py as follows: python setup.py build sudo python setup.py installCreate a
4 min read
How to Connect Python with SQL Database?
Python is a high-level, general-purpose, and very popular programming language. Basically, it was designed with an emphasis on code readability, and programmers can express their concepts in fewer lines of code. We can also use Python with SQL. In this article, we will learn how to connect SQL with Python using the ‘MySQL Connector Python module. T
6 min read
How To Connect and run SQL Queries to a PostgreSQL Database from Python
In this PostgreSQL Python tutorial, we will explain how to connect to a PostgreSQL database using Python and execute SQL queries. Using the powerful psycopg2 library, we can seamlessly interact with our PostgreSQL database from Python, making it easy to perform tasks like inserting, updating, and retrieving data. Whether we're new to Python or a se
4 min read
Connect to MySQL using PyMySQL in Python
In this article, we will discuss how to connect to the MySQL database remotely or locally using Python. In below process, we will use PyMySQL module of Python to connect our database. What is PyMySQL? This package contains a pure-Python MySQL client library, based on PEP 249. Requirements : MySQL Server – one of the following : MySQL >= 5.5Maria
2 min read
Create MySQL Database Login Page in Python using Tkinter
Prerequisites: Python GUI – tkinter, Python MySQL – Select QueryTkinter is one of the Python libraries which contains many functions for the development of graphic user interface pages and windows. Login pages are important for the development of any kind of mobile or web application. This page is most essential for user authentication purposes.We
2 min read
Get the id after INSERT into MySQL database using Python
Prerequisites: MySQL, mysql-connector for python The task here is to draft a Python program that works with SQL support to connect data. Whenever insertion into the database takes place, the ID of the row inserted will be printed. To connect python with the database we are using MySQL connector. The work of mysql-connector is to provide access to M
2 min read
How to visualize data from MySQL database by using Matplotlib in Python ?
Prerequisites: Matplotlib in Python, MySQL While working with Python we need to work with databases, they may be of different types like MySQL, SQLite, NoSQL, etc. In this article, we will be looking forward to how to connect MySQL databases using MySQL Connector/Python. MySQL Connector module of Python is used to connect MySQL databases with the P
5 min read
How to store XML data into a MySQL database using Python?
In this article, we are going to store XML data into the MySQL database using python through XAMPP server. So we are taking student XML data and storing the values into the database. RequirementsXAMPP server: It is a cross-platform web server used to develop and test programs on a local server. It is developed and managed by Apache Friends and is o
3 min read
How to take backup of MySQL database using Python?
In this article, we are going to learn how to back up a MySQL database using python. Database used: Python modules required: In this post, we are going to use the mysql-connector module of python to back up our data. You can install mysql-connector with the following command: pip install mysql-connectorBacking Up Database: So, it's a fairly simple
3 min read
Python MySQL - Create Database
Python Database API ( Application Program Interface ) is the Database interface for the standard Python. This standard is adhered to by most Python Database interfaces. There are various Database servers supported by Python Database such as MySQL, GadFly, mSQL, PostgreSQL, Microsoft SQL Server 2000, Informix, Interbase, Oracle, Sybase etc. To conne
2 min read
How to connect WiFi using Python?
Seeing a computer without an active internet connection today is next to impossible. The Internet has been of the utmost importance in the 21st Century. There are multiple ways one can connect their machine to the Internet. The first being, the traditional cables, i.e. the Ethernet, and the other being, the modern Wireless Fidelity Systems or Wi-Fi
5 min read
How to integrate Mysql database with Django?
Django is a Python-based web framework that allows you to quickly create efficient web applications. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. Installation Let's first understand how to install MySQL to install the Mysql
2 min read
Matplotlib.pyplot.connect() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.connect() Function This method is used to connect an event with string s to a function. Syntax: matplotlib.pyplot.connect(s, func) Parame
3 min read
Connect your android phone camera to OpenCV - Python
Prerequisites: OpenCV OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. Many a time, while doing Computer Vision or Imag
2 min read
Connect new point to the previous point on a image with a straight line in Opencv-Python
OpenCV-Python is a library of Python bindings designed to solve computer vision problems. Let's see how to Connect a new point to the previous point on an image with a straight line. Step 1: Draw points on image: On a image we can mark points using cv2.circle( ) method. This method is used to draw a circle on any image. Syntax: cv2.circle(image, ce
3 min read
HAUS Connect - Python Project
One of the most common problems faced by college students is that we have very erratic timetables and it is a cumbersome task to keep up with them, these issues have been amplified enormously during these pandemic times where everyone is on their own. The purpose of this application is to help students keep track of their classes, tests, and assign
15+ min read
Tableau Drivers - Download and Connect
When working on Tableau, one of the befits a user can have is the option and ease to connect with many different types of data sources. If the user is working on the Tableau desktop edition, then it provides built-in connectivity to the different types of data sources. One can clearly see many different options available to the left side under the
1 min read
Tableau - Connect to a data source
Visualisation in Tableau starts with connecting to an outside data source. This article explains how to connect Tableau to any external data source. Steps to follow - Run Tableau. On the left side of the start screen, there is a Connect Panel. Go to the File Section and choose the type of data file you want. Let's choose any excel file. On clicking
1 min read
How to Connect Mongodb Compass to Flask
An effective GUI tool for managing and visualizing MongoDB data is MongoDB Compass. On the other hand, a well-liked Python web framework for creating web apps is called Flask. Integrating your MongoDB data into your Flask web application may benefit from connecting MongoDB Compass to Flask. Through your Flask web application, you can quickly read,
2 min read
How to Connect Scatterplot Points With Line in Matplotlib?
Prerequisite: Scatterplot using Seaborn in Python Scatterplot can be used with several semantic groupings which can help to understand well in a graph. They can plot two-dimensional graphics that can be enhanced by mapping up to three additional variables while using the semantics of hue, size, and style parameters. And matplotlib is very efficient
2 min read
OAuth Authentication with Flask - Connect to Google, Twitter, and Facebook
In this article, we are going to build a flask application that will use the OAuth protocol to get user information. First, we need to understand the OAuth protocol and its procedure. What is OAuth? OAuth stands for Open Authorization and was implemented to achieve a connection between online services. The OAuth Community Site defines it as “An ope
8 min read
Connect Django Project to MongoDB
Djongo is a SQL to MongoDB query transpiler. Using djongo, we can use MongoDB as a backend database for our Django project. We don't even need to change the Django ORM. The best part is that we can setup Django with MongoDB by adding just one line of code. There is no need to change serializers, views, or any other modules. Official Docs - https://
2 min read
How to Connect ReactJS with flask API ?
Connecting React with Flask API allows us to create a full-stack web application with React handling the user interface at frontend and Flask serving the data in backend. Here React makes the HTTP request to interact with the flask API to perform operations with the database. ApproachTo connect React JS with Flask API we will be using the data fetc
4 min read
How to Create a Backup of a SQLite Database using Python?
In this article, we will learn How to Create a Backup of an SQLite Database using Python. To Create a Backup of an SQLite Database using Python, the required modules are SQLite3 and IO. First, let's create the original database to do that follow the below program: C/C++ Code import sqlite3 import io from sqlite3 import Error def SQLite_connection()
2 min read
Inserting variables to database table using Python
In this article, we will see how one can insert the user data using variables. Here, we are using the sqlite module to work on a database but before that, we need to import that package. import sqlite3 To see the operation on a database level just download the SQLite browser database.Note: For the demonstration, we have used certain values but you
3 min read
Create a database in MongoDB using Python
MongoDB is a general-purpose, document-based, distributed database built for modern application developers and the cloud. It is a document database, which means it stores data in JSON-like documents. This is an efficient way to think about data and is more expressive and powerful than the traditional table model. MongoDB has no separate command to
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg