Creating table and inserting data in MySQL using python (Raspberry Pi 3B+)


This article demonstrates how to execute INSERT Query from python to add a new row to the MySQL database table. I’ve written multiple examples in Python that shows how to INSERT rows into MySQL table.

Goal of this lesson:
1) Creating database
2) Create table for query
3) Create rows and columns   
4) Insert data 
5) fetch data again
python creating table and inserting data in mysql process

Prerequisite

Before moving further, Please make sure you have the following in place: –
  • Username and password that you need to connect MySQL
  • MySQL database table name in which you want to insert data
code:

import MySQLdb
mydb=MySQLdb.connect("localhost", "juhi","juhi")
# connect MySQL with phpmyadmin
cur=mydb.cursor()

#Cursor is a object that communicate the entire mysql server through out we'll able to
create our database
cur.execute("""CREATE DATABASE mydata1""")
#create a database whose name is mydata1
cur.execute("""CREATE TABLE sample""")
#create a table whose name is sample
cur.execute("""INSERT INTO sample(user,host,password)
VALUES("juhi","local host","no")""")
# insert data into the table
cur.execute("select * from sample")

row=cur.fetchone()
#fetch only one data from table
print("Displaying the first row: ", row)
#display frist row

# to fetch all data from table
row=cur.fetchall()
print("Displaying the first row: ", row)

Result in php myadmin:

Result in python IDLE:
User   Host           Password
juhi   localhost       no
Any  linux              no

Next Blog is on how to draw virtual Geometric shape using mouse click on live video using python opencv + mysql + phpmyadmin.  

Comments

Popular posts from this blog

Voice Recognition Using web camera and Google API - Raspberry pi 3B (python)