Hello every one in this article we are going to see how to connect mysql with python. We we try some program related like create database and table, insert data, retrieve data, Update data and Drop the table.
Let’s Us Begin
Table of content :-
- Basics of MySQL.
- How to establish a connection with MySQL and create a database.
- How to create a table and insert values.
- How to retrieve the data and update the data.
- How to drop the table.
Basic of MySQLÂ :-
- MySQL is one of the popular database management systems.
- It is Open-source relational database management.
- It stores data in a table. Tables further store data in rows and columns.
- It is a freely available database system.
- It is a Structured Query Language.
- It can run on Multiple Platforms such as Linux, Windows and UNIX.
- It is a Highly Scalable Database System.
How to establish connection with MySQL and create database :-
As python is a rich programming language there is an inbuilt package for MySQL is called pymysql. At first we will import the package then create the connection object using connect() method whose basic parameters are host ,userpassword and database name
After creating the connection we will create the cursor object using con.cursor() .Basically cursor work between application and database to send and retrieve the data.
Then we have taken the string named Query in which we have stored the query which we want to execute. We will execute the Query using cur.execute() method and always make a habit to commit after execution of query.
After completion of program make sure to close the connection and cursor using close() method
Program :-
How to create table and insert values :-
How to retrieve the data and update the data :-
import pymysql
​
try:
  con = pymysql.connect(host="localhost",user="root",passwd="", database="blog_demo_db")
  cur = con.cursor()
 Â
  print("Before Update")
  query="select * from student"
  cur.execute(query)
  for x in cur:
    print(x)
 Â
  #For Updating
  query="update student set name='john' where enrollment=3"
  cur.execute(query)
  print("\nUpdating...")
 Â
  print("\nAfter Update")
  query="select * from student"
  cur.execute(query)
  for x in cur:
    print(x)
  con.commit()
except:
  print("Query Problem")
​
finally:
  if cur:
    cur.close()
  if con:
    con.close()
0 Comments