OCJP

Python Script to Insert MySQL Data

Hereby we will explain an example to insert data into table of MySQL Database. We have created a database named dbphpdemo and table named tblwebsitedetails in our earlier post of MySQL Connection. We have used import mysql.connector statement to import MySQL Connector in our Script. If you are getting the error like ‘ModuleNotFoundError: No module named ‘mysql” that means you do not have installed MySQL Connector, first install it using command pip install mysql-connector-python-rf  in Command Prompt.

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="",
  database="dbphpdemo"
)

mycursor = mydb.cursor()

sql = "INSERT INTO tblwebsitedetails (strWebsiteName, strWebsiteDetails,dtmCreationDate,intRank) VALUES (%s, %s,%s , %s)"
val = ("https://xyz.com", "Highway 21","2019-01-01","2")
mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")

Leave a Reply

Your email address will not be published. Required fields are marked *


× How can I help you?