Python資料庫編程

來源:互聯網
上載者:User
講解Python操作資料庫,完成簡單的增刪改查工作,以MySQL資料庫為例。

Python的MySQL資料庫操作模組叫MySQLdb,需要額外的安裝下。

通過pip工具安裝:pip install MySQLdb

MySQLdb模組,我們主要就用到串連資料庫的方法MySQLdb.Connect(),串連上資料庫後,再使用一些方法做相應的操作。

MySQLdb.Connect(parameters...)方法提供了以下一些常用的參數:

連線物件返回的connect()函數:

遊標對象也提供了幾種方法:

13.1 資料庫增刪改查

13.1.1 在test庫建立一張user表,並添加一條記錄

>>> conn = MySQLdb.Connect(host='192.168.1.244',user='root',passwd='QHyCTajI',db='test',charset='utf8')>>> cursor = conn.cursor()>>> sql = "create table user(id int,name varchar(30),password varchar(30))">>> cursor.execute(sql)   # 返回的數字是影響的行數0L    >>> sql = "insert into user(id,name,password) values('1','xiaoming','123456')">>> cursor.execute(sql)1L>>> conn.commit()  # 提交事務,寫入到資料庫>>> cursor.execute('show tables')  # 查看建立的表1L>>> cursor.fetchall()  # 返回上一個遊標執行的所有結果,預設是以元組形式返回((u'user',),)>>> cursor.execute('select * from user')           1L>>> cursor.fetchall()((1L, u'xiaoming', u'123456'),)

13.1.2 插入多條資料

>>> sql = 'insert into user(id,name,password) values(%s,%s,%s)'>>> args = [('2','zhangsan','123456'), ('3','lisi','123456'),('4','wangwu','123456')] >>> cursor.executemany(sql, args)3L>>> conn.commit()>>> sql = 'select * from user'>>> cursor.execute(sql)4L>>> cursor.fetchall()((1L, u'xiaoming', u'123456'), (2L, u'zhangsan', u'123456'), (3L, u'lisi', u'123456'), (4L, u'wangwu', u'123456'))

args變數是一個包含多元組的列表,每個元組對應著每條記錄。當查詢多條記錄時,使用此方法,可有效提高插入效率。

13.1.3 刪除使用者名稱xiaoming的記錄

>>> sql = 'delete from user where name="xiaoming"'>>> cursor.execute(sql)                           1L>>> conn.commit()>>> sql = 'select * from user'                   >>> cursor.execute(sql)       3L>>> cursor.fetchall()         ((2L, u'zhangsan', u'123456'), (3L, u'lisi', u'123456'), (4L, u'wangwu', u'123456'))

13.1.4 查詢記錄

>>> sql = 'select * from user' >>> cursor.execute(sql)         3L>>> cursor.fetchone()   # 擷取第一條記錄(2L, u'zhangsan', u'123456')>>> sql = 'select * from user' >>> cursor.execute(sql)         3L>>> cursor.fetchmany(2) # 擷取兩條記錄((2L, u'zhangsan', u'123456'), (3L, u'lisi', u'123456'))

13.1.4 以字典形式返回結果

預設顯示是元組形式,要想返回字典形式,使得更易處理,就用到cursor([cursorclass])中的cusorclass參數。傳入MySQLdb.cursors.DictCursor類:>>> cursor = conn.cursor(MySQLdb.cursors.DictCursor)>>> sql = 'select * from user'>>> cursor.execute(sql)3L>>> cursor.fetchall()({'password': u'123456', 'id': 2L, 'name': u'zhangsan'}, {'password': u'123456', 'id': 3L, 'name': u'lisi'}, {'password': u'123456', 'id': 4L, 'name': u'wangwu'})

13.2 遍曆查詢結果

#!/usr/bin/env python# -*- coding: utf-8 -*-import MySQLdbtry:    conn = MySQLdb.Connect(host='127.0.0.1', port=3306, user='root', passwd='123456', connect_timeout=3, charset='utf8')    cursor = conn.cursor()    sql = "select * from user"    cursor.execute(sql)    for i in cursor.fetchall():        print iexcept Exception, e:    print ("Connection Error: " + str(e))finally:    conn.close()     # python test.py(2L, u'zhangsan', u'123456')(3L, u'lisi', u'123456')(4L, u'wangwu', u'123456')

使用for迴圈遍曆查詢結果,並增加了異常處理。

  • 聯繫我們

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