MySQL python互動

來源:互聯網
上載者:User

標籤:hash   sql   get   raw   模組   wds   utf8   esc   char   

安裝引入模組
  • 安裝mysql模組
sudo apt-get install python-mysql
  • 在檔案中引入模組
import Mysqldb
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-8import MySQLdbtry:    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-8import MySQLdbtry:    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-8import MySQLdbtry:    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-8import MySQLdbtry:    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=utf8import MySQLdbtry:    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=utf8import MySQLdbtry:    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=utf8import MySQLdbclass 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=utf8from 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=utf8from 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-8from MysqlHelper import MysqlHelperfrom hashlib import sha1sname=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 ‘密碼錯誤‘
 

MySQL python互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.