Thursday, February 13, 2020

How to add and show the mysql db values in python

import pymysql

conn=pymysql.connect(host="localhost",user="root",password="",db="my_python")
mycursor=conn.cursor()
print("\nPlease enter your choice\n")
#print
choice=int(input("1.add\n2.show\n"))
if choice==1:
    mycursor.execute("INSERT INTO names(id,name) VALUES(4,'premsir');")
    print("->data inserted")
else :
    mycursor.execute("SELECT * FROM names")
    row = mycursor.fetchone()
    while row is not None:
        print(row)
        row = mycursor.fetchone()

conn.commit()
conn.close()

output:

Please enter your choice


1.add
2.show
2
(1, 'ANIL')
(2, 'rakesh')
(3, 'rakesh1')

(4, 'premsir')


example 2:
import pymysql

conn=pymysql.connect(host="localhost",user="root",password="",db="my_python")
mycursor=conn.cursor()
print("\nPlease enter your choice\n")
#print
while True:
    choice=int(input("1.add\n2.show\n3.show all\n"))
    if choice==1:
        mycursor.execute("INSERT INTO names(id,name) VALUES(6,'premsir1');")
        print("->data inserted")
    elif choice ==2 :
        mycursor.execute("SELECT * FROM names")
        row = mycursor.fetchone()
        while row is not None:
            print(row)
            row = mycursor.fetchone()
    else:
        mycursor.execute("SELECT * FROM names")
        rows = mycursor.fetchall()
        print('Total Row(s):', mycursor.rowcount)
        for row in rows:
            print(row)

conn.commit()
conn.close()

output:
Please enter your choice


1.add
2.show
3.show all


how to insert the data into mysql using python

import pymysql

conn=pymysql.connect(host="localhost",user="root",password="",db="my_python")
mycursor=conn.cursor()
mycursor.execute("INSERT INTO names(id,name) VALUES(1,'ANIL');")
print("->data inserted")

conn.commit()
conn.close()

output:




How to connect phpmyadmin mysql with python


import pymysql

conn=pymysql.connect(host="localhost",user="root",password="",db="my_python")
mycursor=conn.cursor()
mycursor.execute("""CREATE TABLE names
            (id int primary key,
            name varchar(20)
            )               
            """)
conn.commit()
conn.close()

output:

python class topic video