Tags
python
Asked 2 years ago
12 Aug 2021
Views 232
River

River posted

How do I run a MySQL query in Python ?

How do I run a MySQL query in Python ?
hanuman

hanuman
answered Aug 12 '21 00:00

1. install Mysql Database in the system
2. install the following packages

install mysql and mysqlclient

pip install mysql 

and
install mysql-connector

pip install mysql-connector 


now let's run the query, I am assuming that collegesystem DB is already made and a table named studentinfo has already generated

The following code is for inserting new record in the table studentinfo

import mysql.connector as mysql
 
#put   db detail like username , password , and database name 
db = mysql.connect(
    host = "localhost",
    user = "root", 
    passwd = "root",
    database = "stock"

)

cursor = db.cursor()
studentname='james bond'
studentcode='007'
strd='insert into studentinfo (`name`,`code`) values("{0}","{1}");'.format(studentname,studentcode)
cursor.execute(strd)
db.commit()
print(cursor.rowcount, "record inserted")


let me explain code line by line

import needed mysql.connector

import mysql.connector

mysql.connector.connect() function used to connect with MySQL database with given username and password

mysql.connector.connect() return mysql.connector.connection.MySQLConnection object

cursor() return MySQLCursor which execute query
cursor.execute("query goes here")
you can put select , update or insert any query at cursor.execute() method to execute it .

For Your Info(FYI)

additional function like cursor.fetchall() will return all the rows from the last executed statement

Post Answer