python-mysql数据库操作

1. 首先要安装MySQLdb依赖库
2. 示范mysql数据库的 增、删、改、查操作
import MySQLdb

class MySQLHelper():

     def __init__(self):
         self.conn = MySQLdb.connect(host="localhost",port=3306,user="cb",passwd="XXXXXX",db="wuyn",charset="utf8")
         #port 可以不写,默认3306
         self.cursor = self.conn.cursor()
        
     # select 操作
     def select_data(self,sql): 
         n = self.cursor.execute(sql)
         print n
         #成功时候返回n=1        
         print "Id\tName\tAge"  
         for rows in self.cursor.fetchall():     
             print "%s\t%s\t%s"%(rows[0],rows[1],rows[2])
   
     # insert 操作
     def insert_data(self, sql, param):
         n  = self.cursor.execute(sql, param)
         print n
   
     # update 操作
     def update_data(self, sql, param):
         n= self.cursor.execute(sql, param)
         print n

     # delete 操作
     def delete_data(self, sql, param):
         n = self.cursor.execute(sql, param)
         print n

     def __del__(self):
         print 'disconnect from mysqldb!'

mysqlhelper = MySQLHelper()
mysqlhelper.get_data('select * from user_t')

sql = "insert into user_t (id, name, age) values (%s, %s, %s)"
param = (100,"wuyn",24)
mysqlhelper.insert_data(sql,param)

sql = "update user_t set name=%s where id = %d"
param = ("wuyn",3)
mysqlhelper.update_data(sql, param)

sql  = "delete from user_t where id = %d"
param = ( 3 )
mysqlhelper.delete_data(sql, param)

mysqlhelper.insert_data(sql,p
----------------------------------------------------------------------------------------------------------------------

你可能感兴趣的:(python、mysql)