Python使用MySQLdb封裝基本操作類

2021-07-23 11:57:00 字數 4262 閱讀 7457

經常用到python操作mysql資料庫,於是自己封裝了基本操作mysql資料庫的類,持續更新

# -*- coding:utf-8 -*-

import mysqldb

import datetime

import sys

reload(sys)

sys.setdefaultencoding('utf-8')

#封裝mysqldb類基本操作mysqldb

class

mysqldb:

conn = ''

cursor = ''

def__init__

(self,host1='localhost',user1='root',passwd1='www',database1='test',charset1='utf8'):

try:

print

'init_ ok'

self.conn=mysqldb.connect(host=host1,user=user1,passwd=passwd1,db=database1,port=3306,charset=charset1);

self.cursor = self.conn.cursor(mysqldb.cursors.dictcursor)

except mysqldb.error,e:

error = 'connect failed! error (%s): %s' %(e.args[0],e.args[1])

print error

sys.exit()

#針對讀操作返回結果集

def_execute

(self,sql=''):

try:

self.cursor.execute(sql)

records = self.cursor.fetchall()

return records

except mysqldb.error,e:

error = 'mysql execute failed! error (%s): %s' %(e.args[0],e.args[1])

print error

#sys.exit()

#針對更新,刪除,事務等操作失敗時回滾

def_executecommit

(self,sql=''):

try:

self.cursor = self.conn.cursor()

self.cursor.execute(sql)

self.conn.commit()

except mysqldb.error,e:

self.conn.rollback()

error = 'mysql execute failed! error (%s): %s' %(e.args[0],e.args[1])

print error

#sys.exit()

#建立表

#tablename:表名稱,attr_dict:屬性鍵值對,constraint:主外來鍵約束

#attr_dict:

#constraint:primary key(`id`)

def_createtable

(self,table,attr_dict,constraint):

sql = ''

sql_mid = '`id` bigint(11) not null auto_increment,'

for attr,value in attr_dict.items():

sql_mid = sql_mid + '`'+attr + '`'+' '+ value+','

sql = sql + 'create table if not exists %s ('%table

sql = sql + sql_mid

sql = sql + constraint

sql = sql + ') engine=innodb default charset=utf8'

print

'_createtable:'+sql

self._executecommit(sql)

#查詢表內容

#cond_dict:

#order:'order by id desc'

def_select

(self,table,cond_dict='',order=''):

consql = ' '

if cond_dict!='':

for k,v in cond_dict.items():

consql = consql+k+'='+v+' and'

consql = consql + ' 1=1 '

sql = 'select * from %s where '%table

sql = sql + consql + order

print

'_select:'+sql

return self._execute(sql)

#插入單條資料

def_insert

(self,table,attrs,value):

#values_sql = ['%s' for v in attrs]

attrs_sql = '('+','.join(attrs)+')'

values_sql = ' values('+','.join(value)+')'

sql = 'insert into %s'%table

sql = sql + attrs_sql + values_sql

print

'_insert:'+sql

self._executecommit(sql)

#插入多條資料

#attrs:[id,name,...]

#values:[[1,'jack'],[2,'rose']]

def_insertmany

(self,table,attrs,values):

values_sql = ['%s'

for v in attrs]

attrs_sql = '('+','.join(attrs)+')'

values_sql = ' values('+','.join(values_sql)+')'

sql = 'insert into %s'%table

sql = sql + attrs_sql + values_sql

print

'_insertmany:'+sql

try:

print sql

#print values

for i in range(0,len(values),20000):

self.cursor.executemany(sql,values[i:i+20000])

self.conn.commit()

except mysqldb.error,e:

self.conn.rollback()

error = '_insertmany executemany failed! error (%s): %s' %(e.args[0],e.args[1])

print error

sys.exit()

def_now

(self):

now0 = datetime.datetime.now()

now = now0.strftime('%y-%m-%d %h:%m:%s')

print now

def_close

(self):

self.cursor.close()

self.conn.close()

def__del__

(self):

self._close()

if __name__ == '__main__':

a = mysqldb('localhost','root','www','test','utf8')

a._now()

table='test_mysqldb'

attrs=

constraint='primary key(`id`)'

a._createtable(table,attrs,constraint)

col = ['name','age']

val = ['\'xiegonghai\'','25']

a._insert('test_mysqldb',col,val)

print a._select(table)

python下的MySQLdb使用

1.引入mysqldb庫 import mysqldb 2.和資料庫建立連線 conn mysqldb.connect host localhost user root passwd sa db mytable charset utf8 提供的connect方法用來和資料庫建立連線,接收數個引數,返...

python下的MySQLdb使用

python下的mysqldb使用 3.執行sql語句和接收返回值 cursor conn.cursor n cursor.execute sql,param 首先,我們用使用連線物件獲得乙個cursor物件,接下來,我們會使用cursor提供的方法來進行工作.這些方法包括兩大類 1.執行命令,2....

python中使用MySQLdb模組進行操作

mysqldb中主要的類有 connect cursors,excute,executemany 處理過程 先基於connect類建立連線,例項化出乙個連線物件,基於cursors類建立游標,游標相當於開啟檔案時候的指標,基於游標將請求傳送到伺服器端,伺服器端基於游標的某個方法接收此請求,伺服器端處...