Python MySQL(MySQLdb)


From: http://www.yiibai.com/python/python_mysql.html

Python標准的數據庫接口的Python DB-API(包括Python操作MySQL)。大多數Python數據庫接口堅持這個標准。
 
 

Python標准的數據庫接口的Python DB-API。大多數Python數據庫接口堅持這個標准。.

你可以選擇適合您應用的數據庫。 Python數據庫API支持范圍廣泛的數據庫服務器:

  • GadFly
  • mSQL
  • MySQL
  • PostgreSQL
  • Microsoft SQL Server 2000
  • Informix
  • Interbase
  • Oracle
  • Sybase

下面是可用的Python數據庫接口的列表:

Python Database Interfaces and APIs 

你必須下載一個單獨的DB API的模塊,你需要訪問的每個數據庫。例如,如果你需要訪問Oracle數據庫以及MySQL數據庫,你必須下載Oracle和MySQL數據庫模塊.

DB API提供了與數據庫的工作,盡可能使用Python的結構和語法的最低標准。這個API包括以下:

  • 導入API模塊.

  • 獲取與數據庫的連接.

  • 發出SQL語句和存儲過程.

  • 關閉連接

我們這里將僅學習使用MySQL的所有概念,所以讓我們來談談MySQLdb模塊.

什么是MySQLdb?

MySQLdb的是一個接口連接到MySQL數據庫服務器從Python。它實現了Python數據庫API V2.0,並建上的MySQL C API的頂端.

我怎么安裝MySQLdb?

在進行之前,您確認您已經MySQLdb的機器上安裝。只是在你的Python腳本鍵入以下命令並執行它:

#!/usr/bin/python

import MySQLdb

如果它產生以下結果,那么它意味着未安裝MySQLdb模塊:

Traceback (most recent call last):
  File "test.py", line 3, inimport MySQLdb
ImportError: No module named MySQLdb

安裝MySQLdb模塊,MySQLdb的下載頁面下載並進行如下, 

window平台可以到http://www.codegood.com/archives/4下載:

$ gunzip MySQL-python-1.2.2.tar.gz
$ tar -xvf MySQL-python-1.2.2.tar
$ cd MySQL-python-1.2.2
$ python setup.py build
$ python setup.py install

注: 確保你有root權限來安裝上述模塊.

數據庫連接:

連接到一個MySQL數據庫之前確保以下:

  • 你已經創建了一個數據庫TESTDB.

  • 你已經創建了一個EMPLOYEE表在TESTDB中.

  • EMPLOYEE表有以下幾個字段: FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.

  • “testuser的”用戶ID和密碼“test123”設置用來訪問TESTDB。

  • Python模塊MySQLdb在你的機器上正確安裝.

  • 你已通過MySQL的教程,了解MySQL基礎 

例子:

以下是連接MySQL數據庫“TESTDB”例子

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")

# Fetch a single row using fetchone() method.
data = cursor.fetchone()

print "Database version : %s " % data

# disconnect from server
db.close()

而在我的Linux機器運行此腳本,其產生的結果如下.

Database version : 5.0.45

如果連接建立的數據源,然后返回一個Connection對象,並保存成數據庫,為進一步利用,否則DB設置為None。下一步db對象是用來創建一個游標對象,而這又是用來執行SQL查詢.

最后出來之前,它確保數據庫連接被關閉,資源被釋放.

創建數據庫表:

一旦建立一個數據庫連接,我們已經准備好創建表或記錄到數據庫中使用表創建的游標的執行方法.

例子:

首先,讓我們創建數據庫表Employee:

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

# Create table as per requirement
sql = """CREATE TABLE EMPLOYEE (
         FIRST_NAME  CHAR(20) NOT NULL,
         LAST_NAME  CHAR(20),
         AGE INT,  
         SEX CHAR(1),
         INCOME FLOAT )"""

cursor.execute(sql)

# disconnect from server
db.close()

插入操作:

INSERT操作時,需要你想創建一個數據庫表記錄.

例子:

以下是執行SQL INSERT語句創建一個記錄到EMPLOYEE表的例子.

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
         LAST_NAME, AGE, SEX, INCOME)
         VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()

# disconnect from server
db.close()

上面的例子可以寫成如下動態創建SQL查詢:

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
       LAST_NAME, AGE, SEX, INCOME) \
       VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
       ('Mac', 'Mohan', 20, 'M', 2000)
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()

# disconnect from server
db.close()

例子:

下面的代碼段是另一種形式執行,在那里你可以直接傳遞參數:

..................................
user_id = "test123"
password = "password"

con.execute('insert into Login values("%s", "%s")' % \
             (user_id, password))
..................................

讀取操作:

任何databasse讀取運作手段從數據庫中獲取一些有用的信息.

我們的數據庫建立連接后,我們准備進入這個數據庫查詢。我們可以使用fetchone()方法來獲取單個記錄或者fetchAll方法fetech從數據庫表的多個值.

  • fetchone(): 這種方法獲取查詢結果集的下一行。結果集是一個對象時,將返回一個游標對象用於查詢表.

  • fetchall(): 這種方法獲取結果集的所有行。如果某些行已經從結果集中提取,fetchAll()方法檢索結果集的其余行.

  • rowcount: 這是一個只讀屬性,返回受影響的行數execute()方法.

例子:

以下是程序查詢雇員年薪超過1000表的所有記錄.

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.
sql = "SELECT * FROM EMPLOYEE \
       WHERE INCOME > '%d'" % (1000)
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a list of lists.
   results = cursor.fetchall()
   for row in results:
      fname = row[0]
      lname = row[1]
      age = row[2]
      sex = row[3]
      income = row[4]
      # Now print fetched result
      print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
             (fname, lname, age, sex, income )
except:
   print "Error: unable to fecth data"

# disconnect from server
db.close()

這將產生以下結果:

fname=Mac, lname=Mohan, age=20, sex=M, income=2000

更新操作:

對任何數據庫更新操作意味着更新已經可以在數據庫中的一個或多個記錄。以下是更新所有的記錄為“M”SEX的過程。在這里,我們將所有男性年齡增加一年.

例子:

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Prepare SQL query to UPDATE required records
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
                          WHERE SEX = '%c'" % ('M')
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()

# disconnect from server
db.close()

刪除操作:

DELETE操作是必需的,當你想從數據庫中刪除一些記錄。以下是程序刪除雇員的所有記錄,其中年齡超過20歲.

例子:

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()

# disconnect from server
db.close()

執行事務:

事務是機制,以確保數據的一致性,事務應該有以下四個屬性:

  • 原子性: 無論是事務結束或什么也沒有發生在所有.

  • 一致性: 必須啟動一個事務一致的狀態和離開系統是一致的狀態.

  • 隔離性: 在當前事務外,事務的中間結果是不可見的.

  • 持久性: 一旦事務提交,效果是持久的,即使系統發生故障后.

對Python DB API 2.0提供兩種方法來提交或回滾事務.

例子:

你已經看到我們是如何實施事務。這是一次類似的例子:

# Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()

提交操作:

提交是操作給出了一個綠色的信號數據庫來完成的變化,沒有變化,此操作后可以恢復.

下面是一個簡單的例子,調用commit方法.

    db.commit()

回滾操作:

如果您不滿意與一個或更多的變化,你想恢復這些變化完全使用rollback方法.

下面是一個簡單的例子,調用rollback方法.

   db.rollback()

斷開數據庫:

要斷開數據庫連接,使用close()方法.

db.close()

如果連接到一個數據庫是由用戶使用close()方法關閉,任何未完成的事務都將回滾數據庫。然而,您的應用程序,而不是取決於任何DB的低層次的實現細節上,將更好地調用commit或顯式使用rollback.

錯誤處理:

有許多錯誤的來源。舉幾個例子是在執行SQL語句的語法錯誤,連接失敗,或已經取消或完成的語句句柄調用獲取方法.

DB API定義了一些錯誤,必須存在於每個數據庫模塊。下表列出了這些異常.

Exception Description
Warning Used for non-fatal issues. Must subclass StandardError.
Error Base class for errors. Must subclass StandardError.
InterfaceError Used for errors in the database module, not the database itself. Must subclass Error.
DatabaseError Used for errors in the database. Must subclass Error.
DataError Subclass of DatabaseError that refers to errors in the data.
OperationalError Subclass of DatabaseError that refers to errors such as the loss of a connection to the database. These errors are generally outside of the control of the Python scripter.
IntegrityError Subclass of DatabaseError for situations that would damage the relational integrity, such as uniqueness constraints or foreign keys.
InternalError Subclass of DatabaseError that refers to errors internal to the database module, such as a cursor no longer being active.
ProgrammingError Subclass of DatabaseError that refers to errors such as a bad table name and other things that can safely be blamed on you.
NotSupportedError Subclass of DatabaseError that refers to trying to call unsupported functionality.

你的Python腳本應該處理這些錯誤,但在使用上述任何例外之前,確保您的MySQLdb的支持該異常。你可以得到更多關於他們的信息,通過閱讀DB API 2.0規范.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM