PYTHON Database Commands

###To Create Database


import MySQLdb

db = MySQLdb.connect("localhost","root","")

query="create database hackonly"

db.query(query)

db.close()



###To create table


import MySQLdb

db = MySQLdb.connect("localhost","root","","hackonly")


query="CREATE TABLE INFO ( EMAILID  CHAR(20) NOT NULL,PASSWORD  CHAR(20) NOT NULL)"


db.query(query)

db.close()


###To insert record in table

import MySQLdb

db = MySQLdb.connect("localhost","root","","hackonly")

query="INSERT INTO INFO(EMAILID,PASSWORD) VALUES ('s@gmail.com','sarveshwar')"

db.query(query)

db.commit()

db.close()


###To Update in table


import MySQLdb

db = MySQLdb.connect("localhost","root","","hackonly")

query="UPDATE INFO set PASSWORD ='1234' WHERE EMAILID like '%s' " %('s@gmail.com')

db.query(query)

db.commit()

db.close()


###To retrieve single Row

import MySQLdb

db = MySQLdb.connect("localhost","root","","hackonly")

cursor = db.cursor()

query="SELECT * from info"

cursor.execute (query)

row = cursor.fetchone()

print row

cursor.close()

db.close()


### To retrieve Multiple rows

import MySQLdb

db = MySQLdb.connect("localhost","root","","hackonly")

cursor=db.cursor()

query="SELECT * FROM INFO"

cursor.excecute(query)

results = cursor.fetchall()  #fetchrow   

for row in results:      

print row[0]      

print row[1]

 

db.close()


###To DELETE  records

sql = "DELETE FROM INFO WHERE EMAILID like '%s'" % ('s@gmail.com')

 

###To Delete Database

sql =  "drop database hackonly"

Reactions: