Python MySql 操作類

來源:互聯網
上載者:User

標籤:cursor   sel   UI   erro   name   rgs   update   connect   ack   

 Python 2.7

  暫時只用到這麼多,以後用到其他的再補充。

# -*- coding:utf-8 -*-import MySQLdbimport time‘‘‘· MySQL 操作類· V1.0‘‘‘class MySQLClass(object):    def __init__(self,host,user,password,charset="utf8"):        super(MySQLClass, self).__init__()        self.host=host        self.user=user        self.password=password        self.port=3307  # 我這裡MySql連接埠是3307,預設3306        self.charset=charset        try:            self.conn=MySQLdb.connect(host=self.host,user=self.user,passwd=self.password,port=self.port)            self.conn.set_character_set(self.charset)            self.cur=self.conn.cursor()        except MySQLdb.Error as e:            self.printError(e,‘‘)              def getTime(self):        return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))    def printError(self,e,sql):        print("{0} MySQl Error {1}: {2}".format(self.getTime(),e.args[0],e.args[1]))        print(sql)    def setdb(self,db):        try:            self.conn.select_db(db)        except MySQLdb.Error as e:            self.printError(e,‘‘)    #新增    def insert(self,tablename,DicData):        try:            arrParam=[]            arrValue=[]            for key in DicData:                arrParam.append(‘%s‘)                arrValue.append(DicData[key])            strfield=‘`{0}`‘.format(‘`,`‘.join(DicData.keys()))            strParam=‘values({0})‘.format(‘,‘.join(arrParam))            sql=‘insert into {0}({1}) {2};‘.format(tablename,strfield,strParam)            self.cur.execute(sql,tuple(arrValue)) # 單調新增            self.conn.commit()        except MySQLdb.Error as e:            self.printError(e,sql)        #self.conn.close()    #批量新增    def insertBatch(self,tablename,arrFiled,arrTupleValue):        try:            strfield = ‘`{0}`‘.format(‘`,`‘.join(arrFiled))            arrParam=[]            for x in arrFiled:                arrParam.append(‘%s‘)            strParam = ‘values({0})‘.format(‘,‘.join(arrParam))            sql = ‘insert into {0}({1}) {2};‘.format(tablename, strfield, strParam)            self.cur.executemany(sql,tuple(arrTupleValue)) #many 多條新增            self.conn.commit()        except MySQLdb.Error as e:            self.printError(e,‘‘)        #self.conn.close()    #更新語句    def update(self,sql):        try:            self.cur.execute(sql)            self.conn.commit()        except MySQLdb.Error as e:            self.conn.rollback()            self.printError(e,sql)        #self.conn.close()    #查詢單個欄位 返回List    def executeList(self,sql):        try:            result=[]            self.cur.execute(sql)            ds=self.cur.fetchall()            for i,row in enumerate(ds):                result.append(str(row[0]))            return result        except MySQLdb.Error as e:            self.printError(e,sql)db=MySQLClass(‘127.0.0.1‘,‘root‘,‘123456‘)db.setdb(‘test‘)# arr=db.executeList(‘SELECT DISTINCT skuid from commodity‘)# for x in arr:#     print(x)# table=db.insert(‘commodity‘,{‘title‘:‘10‘})# db.conn.commit()# arrTr={‘title‘:‘1‘}# if ‘titl1e‘ in arrTr:#     print (1)# else:#     print (0)arrFiled = [‘name‘, ‘age‘]arrValue=[‘1‘,‘2‘]arrValueS=[]arrValueS.append([1,‘1‘])db.insertBatch(‘test‘,arrFiled,arrValueS)

Python MySql 操作類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.