Python與MySQL交互
阿新 • • 發佈:2018-05-21
mef incr visio gin ger odi window scroll 修改
交互類型
Windows安裝mysql-python:
https://pypi.org/project/MySQL-python/1.2.5/#files
Linux 安裝python-mysql
yum -y install python-devel mysql-devel
引入模塊:
import MySQLdb
查看:
>>> import MySQLdb >>> import tab >>> MySQLdb MySQLdb >>> MySQLdb. MySQLdb.BINARY MySQLdb.__init__( MySQLdb.Binary( MySQLdb.__loader__ MySQLdb.Connect( MySQLdb.__name__ MySQLdb.Connection( MySQLdb.__new__( MySQLdb.DATE MySQLdb.__package__ MySQLdb.DATETIME MySQLdb.__path__ MySQLdb.DBAPISet( MySQLdb.__reduce__( MySQLdb.DataError( MySQLdb.__reduce_ex__( MySQLdb.DatabaseError( MySQLdb.__repr__( MySQLdb.Date( MySQLdb.__revision__ MySQLdb.DateFromTicks( MySQLdb.__setattr__( MySQLdb.Error( MySQLdb.__sizeof__( MySQLdb.FIELD_TYPE MySQLdb.__str__( MySQLdb.IntegrityError( MySQLdb.__subclasshook__( MySQLdb.InterfaceError( MySQLdb.__version__ MySQLdb.InternalError( MySQLdb._mysql MySQLdb.MySQLError( MySQLdb.apilevel MySQLdb.NULL MySQLdb.connect( MySQLdb.NUMBER MySQLdb.connection( MySQLdb.NotSupportedError( MySQLdb.constants MySQLdb.OperationalError( MySQLdb.debug( MySQLdb.ProgrammingError( MySQLdb.escape( MySQLdb.ROWID MySQLdb.escape_dict( MySQLdb.STRING MySQLdb.escape_sequence( MySQLdb.TIME MySQLdb.escape_string( MySQLdb.TIMESTAMP MySQLdb.get_client_info( MySQLdb.Time( MySQLdb.paramstyle MySQLdb.TimeFromTicks( MySQLdb.release MySQLdb.Timestamp( MySQLdb.result( MySQLdb.TimestampFromTicks( MySQLdb.server_end( MySQLdb.Warning( MySQLdb.server_init( MySQLdb.__all__ MySQLdb.string_literal( MySQLdb.__author__ MySQLdb.test_DBAPISet_set_equality( MySQLdb.__class__( MySQLdb.test_DBAPISet_set_equality_membership( MySQLdb.__delattr__( MySQLdb.test_DBAPISet_set_inequality( MySQLdb.__dict__ MySQLdb.test_DBAPISet_set_inequality_membership( MySQLdb.__doc__ MySQLdb.thread_safe( MySQLdb.__file__ MySQLdb.threadsafety MySQLdb.__format__( MySQLdb.times MySQLdb.__getattribute__( MySQLdb.version_info MySQLdb.__hash__(
Connection對象
用於建立與數據庫的連接
創建對象:調用connect()方法
語法:
conn=connect(參數列表)
參數:
參數host:連接的mysql主機,如果本機是‘localhost‘ 參數port:連接的mysql主機的端口,默認是3306 參數db:數據庫的名稱 參數user:連接的用戶名 參數password:連接的密碼 參數charset:通信采用的編碼方式,默認是‘gb2312‘,要求與數據庫創建時指定的編碼一致,否則中文會亂碼
對象的方法
close()關閉連接
commit()事務,所以需要提交才會生效
rollback()事務,放棄之前的操作
cursor()返回Cursor對象,用於執行sql語句並獲得結果
Cursor對象
執行sql語句
創建對象:調用Connection對象的cursor()方法
語法:
cursor1=conn.cursor()
對象的方法
close()關閉
execute(operation [, parameters ])執行語句,返回受影響的行數
fetchone()執行查詢語句時,獲取查詢結果集的第一個行數據,返回一個元組
next()執行查詢語句時,獲取當前行的下一行
fetchall()執行查詢時,獲取結果集的所有行,一行構成一個元組,再將這些元組裝入一個元組返回
scroll(value[,mode])將行指針移動到某個位置
- mode表示移動的方式
- mode的默認值為relative,表示基於當前行移動到value,value為正則向下移動,value為負則向上移動
- mode的值為absolute,表示基於第一條數據的位置,第一條數據的位置為0
對象的屬性
rowcount只讀屬性,表示最近一次execute()執行後受影響的行數
connection獲得當前連接對象
增刪改
創建testInsert.py文件,向學生表中插入一條數據
#encoding=utf-8 import MySQLdb try: conn=MySQLdb.connect(host=‘localhost‘,port=3306,db=‘test1‘,user=‘root‘,passwd=‘mysql‘,charset=‘utf8‘) cs1=conn.cursor() count=cs1.execute("insert into students(sname) values(‘張良‘)") print count conn.commit() cs1.close() conn.close() except Exception,e: print e.message
修改
創建testUpdate.py文件,修改學生表的一條數據
#encoding=utf-8 import MySQLdb try: conn=MySQLdb.connect(host=‘localhost‘,port=3306,db=‘test1‘,user=‘root‘,passwd=‘mysql‘,charset=‘utf8‘) cs1=conn.cursor() count=cs1.execute("update students set sname=‘劉邦‘ where id=6") print count conn.commit() cs1.close() conn.close() except Exception,e: print e.message
刪除
創建testDelete.py文件,刪除學生表的一條數據
#encoding=utf-8 import MySQLdb try: conn=MySQLdb.connect(host=‘localhost‘,port=3306,db=‘test1‘,user=‘root‘,passwd=‘mysql‘,charset=‘utf8‘) cs1=conn.cursor() count=cs1.execute("delete from students where id=6") print count conn.commit() cs1.close() conn.close() except Exception,e: print e.message
sql語句參數化
創建testInsertParam.py文件,向學生表中插入一條數據
#encoding=utf-8 import MySQLdb try: conn=MySQLdb.connect(host=‘localhost‘,port=3306,db=‘test1‘,user=‘root‘,passwd=‘mysql‘,charset=‘utf8‘) cs1=conn.cursor() sname=raw_input("請輸入學生姓名:") params=[sname] count=cs1.execute(‘insert into students(sname) values(%s)‘,params) print count conn.commit() cs1.close() conn.close() except Exception,e: print e.message
其它語句
cursor對象的execute()方法,也可以用於執行create table等語句
建議在開發之初,就創建好數據庫表結構,不要在這裏執行
查詢
查詢一行數據
創建testSelectOne.py文件,查詢一條學生信息
#encoding=utf8 import MySQLdb try: conn=MySQLdb.connect(host=‘localhost‘,port=3306,db=‘test1‘,user=‘root‘,passwd=‘mysql‘,charset=‘utf8‘) cur=conn.cursor() cur.execute(‘select * from students where id=7‘) result=cur.fetchone() print result cur.close() conn.close() except Exception,e: print e.message
查詢多行數據
創建testSelectMany.py文件,查詢一條學生信息
#encoding=utf8 import MySQLdb try: conn=MySQLdb.connect(host=‘localhost‘,port=3306,db=‘test1‘,user=‘root‘,passwd=‘mysql‘,charset=‘utf8‘) cur=conn.cursor() cur.execute(‘select * from students‘) result=cur.fetchall() print result cur.close() conn.close() except Exception,e: print e.message
封裝
觀察前面的文件發現,除了sql語句及參數不同,其它語句都是一樣的
創建MysqlHelper.py文件,定義類
#encoding=utf8 import MySQLdb class MysqlHelper(): def __init__(self,host,port,db,user,passwd,charset=‘utf8‘): self.host=host self.port=port self.db=db self.user=user self.passwd=passwd self.charset=charset def connect(self): self.conn=MySQLdb.connect(host=self.host,port=self.port,db=self.db,user=self.user,passwd=self.passwd,charset=self.charset) self.cursor=self.conn.cursor() def close(self): self.cursor.close() self.conn.close() def get_one(self,sql,params=()): result=None try: self.connect() self.cursor.execute(sql, params) result = self.cursor.fetchone() self.close() except Exception, e: print e.message return result def get_all(self,sql,params=()): list=() try: self.connect() self.cursor.execute(sql,params) list=self.cursor.fetchall() self.close() except Exception,e: print e.message return list def insert(self,sql,params=()): return self.__edit(sql,params) def update(self, sql, params=()): return self.__edit(sql, params) def delete(self, sql, params=()): return self.__edit(sql, params) def __edit(self,sql,params): count=0 try: self.connect() count=self.cursor.execute(sql,params) self.conn.commit() self.close() except Exception,e: print e.message return count
添加
創建testInsertWrap.py文件,使用封裝好的幫助類完成插入操作
#encoding=utf8 from MysqlHelper import * sql=‘insert into students(sname,gender) values(%s,%s)‘ sname=raw_input("請輸入用戶名:") gender=raw_input("請輸入性別,1為男,0為女") params=[sname,bool(gender)] mysqlHelper=MysqlHelper(‘localhost‘,3306,‘test1‘,‘root‘,‘mysql‘) count=mysqlHelper.insert(sql,params) if count==1: print ‘ok‘ else: print ‘error‘
查詢一個
創建testGetOneWrap.py文件,使用封裝好的幫助類完成查詢最新一行數據操作
#encoding=utf8 from MysqlHelper import * sql=‘select sname,gender from students order by id desc‘ helper=MysqlHelper(‘localhost‘,3306,‘test1‘,‘root‘,‘mysql‘) one=helper.get_one(sql) print one
實例:用戶登錄
創建用戶表userinfos
表結構如下
id
uname
upwd
isdelete
註意:需要對密碼進行加密
如果使用md5加密,則密碼包含32個字符
如果使用sha1加密,則密碼包含40個字符,推薦使用這種方式
create table userinfos( id int primary key auto_increment, uname varchar(20), upwd char(40), isdelete bit default 0 );
加入測試數據
插入如下數據,用戶名為123,密碼為123,這是sha1加密後的值
insert into userinfos values(0,‘123‘,‘40bd001563085fc35165329ea1ff5c5ecbdbbeef‘,0);
接收輸入並驗證
創建testLogin.py文件,引入hashlib模塊、MysqlHelper模塊
接收輸入
根據用戶名查詢,如果未查到則提示用戶名不存在
如果查到則匹配密碼是否相等,如果相等則提示登錄成功
如果不相等則提示密碼錯誤
#encoding=utf-8 from MysqlHelper import MysqlHelper from hashlib import sha1 sname=raw_input("請輸入用戶名:") spwd=raw_input("請輸入密碼:") s1=sha1() s1.update(spwd) spwdSha1=s1.hexdigest() sql="select upwd from userinfos where uname=%s" params=[sname] sqlhelper=MysqlHelper(‘localhost‘,3306,‘test1‘,‘root‘,‘mysql‘) userinfo=sqlhelper.get_one(sql,params) if userinfo==None: print ‘用戶名錯誤‘ elif userinfo[0]==spwdSha1: print ‘登錄成功‘ else: print ‘密碼錯誤‘
Python與MySQL交互