MYSQLdb connection in Python

Python Methods and Functions

In this article, I discussed how to connect to mysql database remotely using python. It is very important for any application to store the database on the server for easy access to the data. It is quite difficult to connect to the database remotely because every service provider does not provide remote access to the MySQL database. Here I am using the MySQLdb Python module to connect to our database, which resides on any server that allows remote access.

What is MYSQLdb?

MySQLdb — it is an interface for connecting to a MySQL database server from Python. It implements the Python v2.0 database API and is built on top of the MySQL C API.

Install Packages

 mysql-connector-python mysql-python 

When using anaconda

 conda install -c anaconda mysql-python conda install -c anaconda mysql-connector-python 

else

 pip install MySQL-python pip install MySQL-python-connector 

Import package

 import MYSQLdb 

How to connect to a remote MySQL database using Python?

Before we start, you should know the basics

& # 39; & # 39; & # 39; This code will not run in the pythonengineering IDE
because the module is required
not installed on the IDE. Also this code requires
a remote MySQL database connection with a valid

Hostname, password Dbusername and Dbname & # 39; & # 39; & # 39;  

 
# Module for connecting to MySQL database

import MySQLdb

  
# Function for connecting to MySQL database

def mysqlconnect ():

# Try to connect

try :

db_connection = MySQLdb.connect

( "Hostname " , " dbusername " , "password" , "dbname" )

  # If no connection is established

except :

print ( "Can't connect to database " )

  return 0

# If the connection is successful

print ( "Connected" )

 

  # Create a Cursor object to execute the query

cursor = db_connection.cursor ()

 

# Executing the request

cursor.execute ( "SELECT CURDATE ();" )

 

# Above query gives us the current date

  # Retrieving data

  m = cursor.fetchone ()

  

  # Print result above

print ( "Today 's Date Is" , m [ 0 ])

 

# Closing the database connection

db_connection.close ()

 
# Call a function to connect to our database
mysqlconnect ()

 Connected Today's Date Is 2017-11-14 

# Python code for illustration and creation
# table in the database

import MySQLdb

 
# Open database connection

db = MySQLdb.connect ( "localhost" , "testuser" , "testpassword" , "gfgdb" )

  

cursor = db.cursor ()

 
# Delete table if it already exists using e xecute ()

cursor.execute ( "DROP TABLE IF EXISTS EMPLOYEE" )

 
# Create table as required

sql =   CREATE TABLE EMPLOYEE (

FNAME CHAR ( 20 ) NOT NULL,

LNAME CHAR ( 20 ),

AGE INT )

 

cursor.execute (sql) # table created

  
# disconnect from the server
db.close ()

Thanks to Shaurya Uppal for helpful improvements.



Tutorials