python對MySQL的CRUD

來源:互聯網
上載者:User

標籤:

我是閑的沒事幹,2014過的太浮誇了,部落格也沒寫幾篇,哎~~~ 用這篇來記錄即將逝去的2014

 

python對各種資料庫的各種操作滿大街都是,不過,我還是喜歡我這種風格的,涉及到其它操作,不過重點還是對資料庫的操作。呵~~

 

Python操作Mysql

首先,我習慣將配置資訊寫到設定檔,這樣修改時可以不用原始碼,然後再寫通用的函數供調用

建立一個設定檔,就命名為conf.ini,可以寫各種配置資訊,不過都指明節點(檔案格式要求還是較嚴格的):

[app_info]DATABASE=testUSER=appPASSWORD=123456HOST=172.17.1.1PORT=3306[mail]host=smtp.163.commail_from[email protected].compassword=654321send_to[email protected];[email protected]

 

同目錄下建立檔案db.py,精悍的代碼如下,不解釋:

# -*-coding:utf-8 -*-import MySQLdb   #首先必須裝這兩個包import ConfigParsercf=ConfigParser.ConfigParser()cf.read("conf.ini")DATABASE=cf.get("app_info","DATABASE")USER=cf.get("app_info","USER")PASSWORD=cf.get("app_info","PASSWORD")HOST=cf.get("app_info","HOST")PORT=cf.get("app_info","PORT")def mysql(sql):    try:        conn=MySQLdb.connect(host=HOST,user=USER,passwd=PASSWORD,db=DATABASE,port=PORT)        cur = conn.cursor()        cur.execute(sql)        rows = cur.fetchall()        conn.commit()  #這個對於增刪改是必須的,否則事務沒提交執行不成功        cur.close()        conn.close()        return rows    except MySQLdb.Error,e:        print "Mysql Error %d: %s" % (e.args[0], e.args[1])

上面是封裝了操作資料庫的方法,只需提供一個sql語句,CRUD均可操作。下面來YY一些資料來測試下增刪改查的具體用法(easy的,我真是閑),接著上面的代碼寫:

def operation():    #查詢    select = mysql(‘select * from test‘)    #插入    ‘‘‘    插入這個地方有2點需要注意:    1.插入某幾列如下指定,插入全部可以不指定列,但必須後面插入的值要按順序    2.注意下面的type列兩邊有反斜點,這是因為type在我這個資料庫裡有個表也叫這個,或者可以把它叫關鍵字,不加反斜點插入會失敗    3.這沒好說的,呵呵,數字預留位置用%d,字串用%s,且字串預留位置必須用雙引號括起來    ‘‘‘    insert = mysql(‘insert into test (name,number,`type`) values("%s",%d,"%s")‘%(‘jzhou‘,100,‘VIP‘))    #更新    mysql(‘update test set number=%d where name="%s"‘%(99,‘jzhou‘))    #刪除    delete = mysql(‘delete from test where number = %d and `type`="%s"‘%(100,‘jzhou‘))    return select #我返回這個是為了下面發送郵件用的,順便增加個發送郵件的功能

我只是想把這個簡單的操作搞的複雜點,增加個發送郵件的功能,也是接著上面的代碼:

mailto_list=[]send_info=cf.get("mail","send_to")send_array=send_info.split(";")for i in range(len(send_array)):    mailto_list.append(send_array[i])mail_host=cf.get("mail","host")mail_from=cf.get("mail","mail_from")mail_password=cf.get("mail","password")def send_mail(to_list,sub,content):    me=mail_from    msg=MIMEText(content,_subtype=‘html‘,_charset=‘utf-8‘)    msg[‘Subject‘]=sub    msg[‘From‘]=me    msg[‘To‘]=";".join(to_list)    try:        s=smtplib.SMTP()        s.connect(mail_host)        s.login(mail_from,mail_password)        s.sendmail(me,to_list,msg.as_string())        s.close()        return True    except Exception,e:        print str(e)        return False

發送郵件的配置我也是寫在conf.ini裡的,在主函數裡調用一下發送郵件來結束這個東西:

if __name__ == ‘__main__‘:    sub = u‘不要問我為什麼寫這篇部落格,閑,就是任性!‘    content = operation()    if send_mail(mailto_list,sub,content):        print ‘send success‘    else:        print ‘send failed‘

 

其實我還想說一下python操作postgresql,跟mysql非常類似,下載包psycopg2,不太相同的就是postgresql中執行的sql語句都要加雙引號,來感受一下:

# -*-coding:utf-8 -*-import psycopg2import ConfigParsercf=ConfigParser.ConfigParser()cf.read("conf.ini")DATABASE=cf.get("cmdb_info","DATABASE")USER=cf.get("cmdb_info","USER")PASSWORD=cf.get("cmdb_info","PASSWORD")HOST=cf.get("cmdb_info","HOST")PORT=cf.get("cmdb_info","PORT")def psql(sql):    try:        conn = psycopg2.connect(database=DATABASE, user=USER, password=PASSWORD, host=HOST, port=PORT)        cur = conn.cursor()        cur.execute(sql)        rows = cur.fetchall()        conn.commit()        cur.close()        conn.close()        return rows    except Exception,e:        print edef psql_oper():    sql="select \"name\",\"type\" from \"test\" where \"name\" = ‘jzhou‘"    rows=psql(sql)    print rows

 

我總結了下,此部落格雖簡單,但包含三個重要的知識點,^_^

1、python讀取ini檔案(要import ConfigParser)

2、python操作mysql

3、發送郵件

 

python對MySQL的CRUD

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.