A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/connect-to-mysql-using-pymysql-in-python/ below:

Connect to MySQL using PyMySQL in Python

Connect to MySQL using PyMySQL in Python

Last Updated : 05 Sep, 2020

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 :

Installation :

This module does not come built-in with Python. You have to install it externally. To install this type the below command in the terminal.

pip install PyMySQL
Connecting to MySQL

The proper way to get an instance of this class is to call connect() method. This method establishes a connection to the MySQL database and accepts several arguments:

Parameters :

Example 1: Let's connect to the MySQL server. 

Python3
import pymysql

def mysqlconnect():
    # To connect MySQL database
    conn = pymysql.connect(
        host='localhost',
        user='root', 
        password = "pass",
        db='College',
        )
    
    cur = conn.cursor()
    cur.execute("select @@version")
    output = cur.fetchall()
    print(output)
    
    # To close the connection
    conn.close()

# Driver Code
if __name__ == "__main__" :
    mysqlconnect()

Output :

(('5.7.30-0ubuntu0.18.04.1',),)

Example 2: Let's try to access a table from the database

Table used:

Python3
import pymysql

def mysqlconnect():
    # To connect MySQL database
    conn = pymysql.connect(
        host='localhost',
        user='root', 
        password = "pass",
        db='College',
        )
    
    cur = conn.cursor()
    
    # Select query
    cur.execute("select * from STUDENT")
    output = cur.fetchall()
    
    for i in output:
        print(i)
    
    # To close the connection
    conn.close()

# Driver Code
if __name__ == "__main__" :
    mysqlconnect()

Output:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4