python database connection

Before connecting to the database, please confirm the following:

We have created a database, table, and user name, password

The Python MySQLdb modules have been installed.

Database Connectivity:

import MySQLdb
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
sql = """CREATE TABLE EMPLOYEE (
         FIRST_NAME  CHAR(20) NOT NULL,
         LAST_NAME  CHAR(20),
         AGE INT,  
         SEX CHAR(1),
         INCOME FLOAT )"""
cursor.execute(sql)
db.close()

 

Create a database table:

import MySQLdb
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print "Database version : %s " % data
db.close()

Data inserted:

import MySQLdb
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
cursor = db.cursor()
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
         LAST_NAME, AGE, SEX, INCOME)
         VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
   cursor.execute(sql)
   db.commit()
except:
db.close()

data query:

import MySQLdb
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
cursor = db.cursor()
sql = "SELECT * FROM EMPLOYEE \
       WHERE INCOME > %s" % (1000)
try:
   cursor.execute(sql)
   results = cursor.fetchall()
   for row in results:
      fname = row[0]
      lname = row[1]
      age = row[2]
      sex = row[3]
      income = row[4]
      print "fname=%s,lname=%s,age=%s,sex=%s,income=%s" % \
             (fname, lname, age, sex, income )
except:
   print "Error: unable to fecth data"
db.close()

Data Update:

import MySQLdb
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
cursor = db.cursor()
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
try:
   cursor.execute(sql)
   db.commit()
except:
   db.rollback()
db.close()

Data Delete:

import MySQLdb
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
cursor = db.cursor()
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
try:
   cursor.execute(sql)
   db.commit()
except:
   db.rollback()
db.close()

Guess you like

Origin www.cnblogs.com/huanghuangwei/p/12044602.html