Python對MySQL的CRUD

來源:互聯網
上載者:User

Python對MySQL的CRUD

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

Python操作MySQL

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

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

[app_info]
DATABASE=test
USER=app
PASSWORD=123456
HOST=172.17.1.1
PORT=3306

[mail]
host=smtp.bkjia.com
mail_from=bkjia0111@bkjia.com
password=654321
send_to=bkjia0111@bkjia.com;bkjia0111@bkjia.com

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

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

import MySQLdb  #首先必須裝這兩個包
import ConfigParser

cf=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 psycopg2
import ConfigParser

cf=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 e

def 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發送郵件

4、發表出來的都是經過實踐檢驗的,即使很簡單,這是一種態度!

--------------------------------------分割線 --------------------------------------

CentOS上源碼安裝Python3.4 

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版]

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼]

Python指令碼擷取Linux系統資訊

在Ubuntu下用Python搭建案頭演算法交易研究環境

Python 語言的發展簡史

Python 的詳細介紹:請點這裡
Python 的:請點這裡 

本文永久更新連結地址:

相關文章

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.