簡單封裝MySQLdb模塊操作MySQL數據庫

1. python連接mysql的connector有很多,我們選擇MySQLdb

2. 讓python支持MySQLdb模塊

#pip2.7 install MySQL-python

3. 查看python2.7可使用的模塊是否存在MySQLdb

# ipython
WARNING: IPython History requires SQLite, your history will not be saved
Python 2.7.11 (default, Mar 10 2016, 09:45:30) 
Type "copyright", "credits" or "license" for more information.

IPython 4.1.2 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.
In [1]: help('modules')
Please wait a moment while I gather a list of all available modules...

MySQLdb             calendar            marshal


4. 簡單封裝的模塊,測試沒問題

script-name:mysql-conn.py

#!/usr/bin/python27
#-*-coding:utf-8-*-

#導入MySQL驅動原生模塊
import MySQLdb  

class mysqldb():
        #構造器設定初始值
	def __init__(self,host='192.168.17.1',port=4306,user='root',passwd='zcy'):  
		self.host = host
		self.port = port
		self.user = user
		self.passwd = passwd
		#實例一開始就具備了連接和遊標屬性
		self.conn1 = MySQLdb.connect(host=self.host,port=self.port,user=self.user,passwd=self.passwd)  
		self.cur1 = self.conn1.cursor()
         
         #定義mysql中的Select查詢語句
	def find(self,field,db,table):  
		"""
			field -> query field
			db -> query database
			table -> query table
		"""
		self.field = field
		self.db = db
		self.table = table
		self.cur1.execute('select ' + self.field + ' from ' + self.db + '.' + self.table)
		return self.cur1.fetchall()
		
		#建庫
	def createdb(self,db):  
		self.cur1.execute('create database if not exists ' + db)
	       
	        #建表
	def createtable(self,db,table):   
		self.conn1.select_db(db)
		self.cur1.execute(
		'''
		    create table ''' + table + ''' (
				id int(5) not null primary key auto_increment,
				name char(10) not null,
				phone varchar(12) not null,
				class char(20)
			);			
		 ''')
                
                #插入數據
	def insert(self,db,table,*l): 
		self.cur1.execute('insert into '+ db + '.' + table +  ' values(null,%s,%s,%s)' , *l)
		self.conn1.commit()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章