1. 程式人生 > >Python資料庫操作(MySQL)

Python資料庫操作(MySQL)

嗯...這兩天搗鼓了一下Python,不得不說指令碼語言就是強大方便,隨手開啟cmd,敲一行跑一行,媽媽再也不用擔心我打不開編譯器了......(這是針對一些配置中下的電腦開啟AS說的...)

好...今天先記錄一下Python的MYSQL資料庫操作吧。其實很簡單,第一步,我們需要安裝一個mysql for python的外掛,下載地址如下:MySQL for python 下載地址

然後,我們需要import MySQLdb,然後就可以呼叫其api進行資料庫程式設計了。

1. 資料庫的連線

我們先使用MySQL新建一個數據庫和一個表,在我的電腦上,新建了一個worm.db,其中又新建了一個worm_tb表,該表中有兩個欄位,分別是id和url,其中id是primary key auto_increment。

使用python連線MySQL資料庫的方法和簡單,只需要呼叫一個api即可:

	self.conn = MySQLdb.connect(
									host = 'localhost',
									user = 'root',
									passwd = '',
									db = 'worm'
									)
		self.cursor = self.conn.cursor()
呼叫connect介面連線MySQL資料饋時,我們至少需要給定4個引數,分別是host,user,passwd和db,如程式碼所示。我們看到,上述程式碼呼叫conn物件的cursor()介面獲得了一個cursor物件,這個東西是幹嘛的呢?cursor是一個遊標物件,其用來對資料庫進行“增刪減除”等操作,並返回操作結果。下面我們會看到我們就是利用cursor物件來進行資料庫查詢的。

2. 資料庫查詢

資料庫操作使用的是上述得到的cursor物件的execute方法。我們看示例程式碼。

	def getData(self):
		data=[]
		self.cursor.execute(r"select url from worm_tb")
		if self.cursor.rowcount != 0:
			result = self.cursor.fetchall()
			for d in result:
				data.append(d[0])
		return data

上述程式碼定義了一個查詢資料的方法,我們看到,我們可以利用cursor提供的execute方法執行一條select語句,該方法返回受影響的條數。然後我們還可以查詢cursor的rowcount屬性獲得查詢結果條數,最後呼叫fetchall方法獲得全部資料,該方法返回一個tuple。除了fetchal方法外,還有一個fetchone()方法,可以逐條獲取結果。

同樣的,執行資料庫刪除,插入,更新操作也是呼叫cursor物件的execute方法執行對應的sql語句即可。下面給出一個插入資料的示例程式碼。

	def insert(self,url):
		try:
			self.cursor.execute(r"insert into worm_tb (url) values ('%s')" % url)
			self.conn.commit()
		except Exception as e:
			print e
			self.conn.rollback()
從上面的程式碼我們看到了兩個上面沒有提到的方法,那就是conn物件的commit()方法和rollback()方法。這兩個方法一般配套使用。用過其它程式語言進行資料庫程式設計的童鞋應該可以猜到這是幹嘛用的。沒錯,這是用於事務操作的,分別是提交事務和回滾事務。其配合try-except使用口味最佳哦。

我們先執行上面的insert方法插入資料,然後再執行getdata方法獲取資料,可以得到結果如下:

3. 編寫成一個類

我們可以將資料庫的操作封裝成一個類,以方便我們進行編碼設計。

# -*- coding:utf-8 -*-
import MySQLdb

class Databse(object):
	def __init__(self):
		self.conn = MySQLdb.connect(
									host = 'localhost',
									user = 'root',
									passwd = '',
									db = 'worm'
									)
		self.cursor = self.conn.cursor()

	def getData(self):
		data=[]
		self.cursor.execute(r"select url from worm_tb")
		if self.cursor.rowcount != 0:
			result = self.cursor.fetchall()
			for d in result:
				data.append(d[0])
		return data

	def insert(self,url):
		try:
			self.cursor.execute(r"insert into worm_tb (url) values ('%s')" % url)
			self.conn.commit()
		except Exception as e:
			print e
			self.conn.rollback()

	def die(self):
		self.cursor.close()
		self.conn.close()


if __name__ == '__main__':
	db = Databse()
	db.insert('www.baidu.com')
	print db.getData()
	db.die()

上述程式碼封裝了對worm_tb的select和insert操作,讀者可以在此基礎上編寫update和delete操作甚至更多。