bottle架構學習(八)之Mysql資料庫的操作

來源:互聯網
上載者:User

標籤:bottle   資料庫   python   web開發   

MySQLdb 是用於Python串連Mysql資料庫的介面。

安裝MySQLdb

[[email protected] bottle]# yum install MySQL-python –y

如果使用編譯安裝請到這裡下載安裝包https://pypi.python.org/pypi/MySQL-python並執行以下命令

[[email protected] bottle]# gunzip  MySQL-python-1.2.3.tar.gz[[email protected] bottle]# tar  xf  MySQL-python-1.2.3.tar[[email protected] bottle]# cd MySQL-python-1.2.3[[email protected] bottle]# python setup.py build[[email protected] bottle]# python setup.py install

 

資料庫連接

直接上代碼:

[[email protected] bottle]# cat linkmysql.py#!/usr/bin/env python#coding=utf-8import MySQLdb db =MySQLdb.connect("localhost","root","123","mytestdb") #開啟資料庫連接cursor = db.cursor()                   #使用cursor()方法擷取操作遊標cursor.execute("SELECTVERSION()")      #使用execute方法執行SQL語句data = cursor.fetchone()               #使用fetchone()方法擷取一條資料。print "Database version : %s " %datadb.close()                             #關閉資料庫連接


建立資料庫表

[[email protected] bottle]# cat create_table.py#!/usr/bin/env python#encoding=utf-8import MySQLdb db =MySQLdb.connect("localhost","root","123","mytestdb")cursor = db.cursor()cursor.execute("DROP TABLE IF EXISTSMYTABLE")#如果MYTABLE表已經存在則使用execute()方法刪除。sql = """CREATE TABLE MYTABLE(        FIRST_NAME CHAR(20) NOT NULL,        LAST_NAME CHAR(20),        AGE INT,         SEX CHAR(1),        INCOME FLOAT )"""cursor.execute(sql)db.close()

 

資料庫插入操作

[[email protected] bottle]# cat insert.py#!/usr/bin/env python#encoding=utf-8import MySQLdb db =MySQLdb.connect("localhost","root","123","mytestdb")cursor = db.cursor()sql = """INSERT INTOMYTABLE(FIRST_NAME,        LAST_NAME, AGE, SEX, INCOME)        VALUES (‘Mac‘, ‘Mohan‘, 20, ‘M‘, 2000)""" #上述sql語句也可以寫成以下形式。#sql = "INSERT INTOMYTABLE(FIRST_NAME, #      LAST_NAME, AGE, SEX, INCOME) #      VALUES (‘%s‘, ‘%s‘, ‘%d‘, ‘%c‘, ‘%d‘ )" % #      (‘Mac‘, ‘Mohan‘, 20, ‘M‘, 2000) try:  cursor.execute(sql)  db.commit()    #提交到資料庫執行except:  db.rollback()    #如果執行錯誤則復原cursor.execute(sql)db.close()

 

資料庫查詢操作

Python查詢Mysql使用 fetchone()方法擷取單條資料, 使用fetchall() 方法擷取多條資料。

fetchone(): 該方法擷取下一個查詢結果集。結果集是一個對象

fetchall():接收全部的返回結果行.

rowcount: 這是一個唯讀屬性,並返回執行execute()方法後影響的行數。

[[email protected] bottle]# cat query.py#!/usr/bin/env python#encoding=utf-8import MySQLdb db =MySQLdb.connect("localhost","root","123","mytestdb")cursor = db.cursor()sql = "SELECT * FROM MYTABLE WHEREINCOME > ‘%d‘" % (1000) try:  cursor.execute(sql)  results = cursor.fetchall() #擷取所有記錄列表  for row in results:     fname = row[0]     lname = row[1]     age = row[2]     sex = row[3]     income = row[4]     # 列印結果     print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" %             (fname, lname, age, sex, income )except:  print "Error: unable to fecth data" cursor.execute(sql)db.close()

 

資料庫更新操作

[[email protected] bottle]# cat update.py#!/usr/bin/env python#encoding=utf-8import MySQLdb db =MySQLdb.connect("localhost","root","123","mytestdb")cursor = db.cursor()sql = "UPDATE MYTABLE SET LAST_NAME =‘XIAOMING‘ WHERE INCOME = ‘%s‘" % (‘2000‘)try:  cursor.execute(sql)  db.commit()except:  db.rollback()cursor.execute(sql)db.close()

 

執行事務

事務機制可以確保資料一致性。

 

事務應該具有4個屬性:原子性、一致性、隔離性、持久性。這四個屬性通常稱為ACID特性。

原子性(atomicity)。一個事務是一個不可分割的工作單位,事務中包括的諸操作要麼都做,要麼都不做。

一致性(consistency)。事務必須是使資料庫從一個一致性狀態變到另一個一致性狀態。一致性與原子性是密切相關的。

隔離性(isolation)。一個事務的執行不能被其他事務幹擾。即一個事務內部的操作及使用的資料對並發的其他事務是隔離的,並發執行的各個事務之間不能互相干擾。

持久性(durability)。持久性也稱永久性(permanence),指一個事務一旦提交,它對資料庫中資料的改變就應該是永久性的。接下來的其他動作或故障不應該對其有任何影響。

 

Python DB API 2.0 的事務提供了兩個方法 commit 和 rollback。



這篇部落格跟bottle架構本身關係不大,但是操作資料庫又是web開發必不可少的,所以就跟bottle放到一起了。


本文出自 “乾楠有” 部落格,請務必保留此出處http://changfei.blog.51cto.com/4848258/1664025

bottle架構學習(八)之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.