How to connect MySQL DB with Python - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we’ll see a step by step guide on how to connect MySQL Database with Python and will execute a query using Python.
We need to install some of the tools before making a connection between MySQL Databases and Python.

MySQL Server and workbench. (one endpoint) – To correctly set up MySQL server and workbench, Follow the steps provided in this tutorial. After setup, Open the workbench and it should look something like this.

MySQL Server and workbench. (one endpoint) – To correctly set up MySQL server and workbench, Follow the steps provided in this tutorial. After setup, Open the workbench and it should look something like this.

Install Python, here you can find the step by step guide to install python on windows
MySQL-Python-Connector (Connection medium) – This acts as a connection medium between both MySQL Databases and Python. To install this, go to Windows PowerShell and run the following pip command.

Install Python, here you can find the step by step guide to install python on windows
MySQL-Python-Connector (Connection medium) – This acts as a connection medium between both MySQL Databases and Python. To install this, go to Windows PowerShell and run the following pip command.
Now our MySQL server is running and connector is installed on the machine, Next step is to use Python to connect to a MySQL Database.
We have to import the connector that we have installed.
import mysql.connector as mysqlConnector
We will use the connect() method of the connector to connect to the instance. This method takes several arguments.
host – This is the name of the host on which server is running. Since we are running on localhost, we will use localhost as its value.
user – This is the name of the user while setting up the MySQL Server. In our case, we have used the name root.
password – Password that is set while setting up the MySQL Server. In our case, we have used the root as a password.
databases – It takes the name of the database that we wish to connect.
conn = mysqlConnector.connect(host='localhost',user='root',passwd='root')
To check whether the connection is successful or not we can use a simple if-else condition.
if conn:
    print("Connection Successful :)")
else:
    print("Connection Failed :(")
Output:
Connection Successful :)
Now we have successfully connected to the MySQL Instance, Next step is to run SQL queries which will output a resultset. To traverse through the result set we need to create a cursor.
cur = conn.cursor()
Now we can use this cursor object to execute a SQL Query and traverse the resultset using the loops. Let us run a command to show the pre-defined databases in MySQL. In Python, we can use execute() function which takes a SQL Query as a string that we want to run.
cur.execute("SHOW DATABASES")
for row in cur:
    print(row)
Output:
('information_schema',)
('mysql',)
('performance_schema',)
('sys',)
After completing the work, It is important to close the connection that we have made in the end using the close() method.
conn.close()
In this tutorial, we have successfully learned how to connect MySQL DB to Python and executed a SQL query successfully.
How to connect MySQL Database in Eclipse
Install Mysql on Windows 10 Step by Step
Cursors in SQL
Happy Learning 🙂

Install Mysql on Windows 10 Step by Step
How to Remove Spaces from String in Python
Insert an Image using JDBC in Mysql DB
How to connect MySQL Database in Eclipse
Python raw_input read input from keyboard
How to access for loop index in Python
How install Python on Windows 10
What are Python default function parameters ?
MySQL Create Table Syntax Example
MySQL Unique Constraint Syntax Example
How to Export MySQL Tables to a file from command line
Python – How to remove duplicate elements from List
How to get Words Count in Python from a File
How to get Characters Count in Python from a File
How to merge two lists in Python

Install Mysql on Windows 10 Step by Step
How to Remove Spaces from String in Python
Insert an Image using JDBC in Mysql DB
How to connect MySQL Database in Eclipse
Python raw_input read input from keyboard
How to access for loop index in Python
How install Python on Windows 10
What are Python default function parameters ?
MySQL Create Table Syntax Example
MySQL Unique Constraint Syntax Example
How to Export MySQL Tables to a file from command line
Python – How to remove duplicate elements from List
How to get Words Count in Python from a File
How to get Characters Count in Python from a File
How to merge two lists in Python
 


Δ
 Python – Introduction
 Python – Features
 Python – Install on Windows
 Python – Modes of Program
 Python – Number System
 Python – Identifiers
 Python – Operators
 Python – Ternary Operator
 Python – Command Line Arguments
 Python – Keywords
 Python – Data Types
 Python – Upgrade Python PIP
 Python – Virtual Environment
 Pyhton – Type Casting
 Python – String to Int
 Python – Conditional Statements
 Python – if statement
 Python – *args and **kwargs
 Python – Date Formatting
 Python – Read input from keyboard
 Python – raw_input
 Python – List In Depth
 Python – List Comprehension
 Python – Set in Depth
 Python – Dictionary in Depth
 Python – Tuple in Depth
 Python – Stack Datastructure
 Python – Classes and Objects
 Python – Constructors
 Python – Object Introspection
 Python – Inheritance
 Python – Decorators
 Python – Serialization with Pickle
 Python – Exceptions Handling
 Python – User defined Exceptions
 Python – Multiprocessing
 Python – Default function parameters
 Python – Lambdas Functions
 Python – NumPy Library
 Python – MySQL Connector
 Python – MySQL Create Database
 Python – MySQL Read Data
 Python – MySQL Insert Data
 Python – MySQL Update Records
 Python – MySQL Delete Records
 Python – String Case Conversion
 Howto – Find biggest of 2 numbers
 Howto – Remove duplicates from List
 Howto – Convert any Number to Binary
 Howto  – Merge two Lists
 Howto – Merge two dicts
 Howto – Get Characters Count in a File
 Howto – Get Words Count in a File
 Howto – Remove Spaces from String
 Howto –  Read Env variables
 Howto – Read a text File
 Howto – Read a JSON File
 Howto –  Read Config.ini files
 Howto – Iterate Dictionary
 Howto – Convert List Of Objects to CSV
 Howto – Merge two dict in Python
 Howto – create Zip File
 Howto – Get OS info
 Howto – Get size of Directory
 Howto – Check whether a file exists
 Howto –  Remove key from dictionary
 Howto – Sort Objects
 Howto – Create or Delete Directories
 Howto – Read CSV File
 Howto – Create Python Iterable class
 Howto – Access for loop index
 Howto – Clear all elements from List
 Howto – Remove empty lists from a List
 Howto – Remove special characters from String
 Howto – Sort dictionary by key
 Howto – Filter a list
 Install Java on Mac OS
 Install AWS CLI on Windows
 Install Minikube on Windows
 Install Docker Toolbox on Windows
 Install SOAPUI on Windows
 Install Gradle on Windows
 Install RabbitMQ on Windows
 Install PuTTY on windows
 Install Mysql on Windows
 Install Hibernate Tools in Eclipse
 Install Elasticsearch on Windows
 Install Maven on Windows
 Install Maven on Ubuntu
 Install Maven on Windows Command
 Add OJDBC jar to Maven Repository
 Install Ant on Windows
 Install RabbitMQ on Windows
 Install Apache Kafka on Ubuntu
 Install Apache Kafka on Windows