標籤:comm 安裝mysql word 建立 命令 調用 none 亂碼 color
一、安裝mysql
二、安裝第三方模組(python2.7下)
三、建立資料庫
四、資料庫的增、刪、改、查
五、封裝
1.1 首先安裝mysql
sudo apt-get install mysql-server mysql-client
1.2 mysql的啟動、停止、重啟
service mysql startservice mysql stopservice mysql restart
1.3 允許遠端連線
1.找到mysql設定檔並修改sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf# bind-address=127.0.0.12.登入mysql,運行命令 grant all privileges on *.* to ‘root‘@‘%‘ identified by ‘mysql‘ with grant option;flush privileges;
3.重啟 mysql
2.1 安裝mysql模組
sudo pip install MySQL-python
pip install pymysql(python3)
2.2 建立與資料庫的串連
1.建立對象:調用connect()方法conn=connect(參數列表)
- 參數host:串連的mysql主機,如果本機是‘localhost‘
- 參數port:串連的mysql主機的連接埠,預設是3306
- 參數db:資料庫的名稱
- 參數user:串連的使用者名稱
- 參數password:串連的密碼
- 參數charset:通訊採用的編碼方式,預設是‘gb2312‘,要求與資料庫建立時指定的編碼一致,否則中文會亂碼
2.3 對象的方法
- close()關閉串連
- commit()事務,所以需要提交才會生效
- rollback()事務,放棄之前的操作
- cursor()返回Cursor對象,用於執行sql語句並獲得結果
執行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
2.4 對象的屬性
- rowcount唯讀屬性,表示最近一次execute()執行後受影響的行數
- connection獲得當前連線物件
3.1 在student資料庫中建立users表
使用sha1加密
create table users( id int primary key auto_increment, uname varchar(20), upwd char(40), isdelete bit default 0);
3.2 加入測試資料
INSERT INTO users(`id`, `uname`, `upwd`, `isdelete`) VALUES (1, ‘user1‘, ‘40bd001563085fc35165329ea1ff5c5ecbdbbeef‘, b‘0‘);INSERT INTO users(`id`, `uname`, `upwd`, `isdelete`) VALUES (2, ‘user2‘, ‘51eac6b471a284d3341d8c0c63d0f1a286262a18‘, b‘0‘);
4.1 增加、修改、刪除
1 # encoding=utf-8 2 import MySQLdb 3 4 try: 5 conn = MySQLdb.connect(host=‘localhost‘, port=3306, db=‘student‘, user=‘root‘, passwd=‘root‘, charset=‘utf8‘) 6 cur = conn.cursor() 7 # 增加 8 sql1 = "insert into users(id,uname) values(3,‘張三‘)" 9 # 修改10 # sql = "update users set uname=‘李四‘ where id=4"11 # 刪除12 # sql = "delete from users where id=5"13 count = cur.execute(sql)14 conn.commit()15 cs1.close()16 conn.close()17 except Exception as e:18 print e.message
4.2 查詢
1. 查詢一行資料#encoding=utf8import MySQLdbtry: conn=MySQLdb.connect(host=‘localhost‘,port=3306,db=‘student‘,user=‘root‘,passwd=‘mysql‘,charset=‘utf8‘) cur=conn.cursor() cur.execute(‘select * from users where id=1‘) result=cur.fetchone() print result cur.close() conn.close()except Exception,e: print e.message2. 查詢多行資料#encoding=utf8import MySQLdbtry: conn=MySQLdb.connect(host=‘localhost‘,port=3306,db=‘student‘,user=‘root‘,passwd=‘mysql‘,charset=‘utf8‘) cur=conn.cursor() cur.execute(‘select * from users‘) result=cur.fetchall() print result cur.close() conn.close()except Exception,e: print e.message
5.1 封裝
# encoding=utf8import MySQLdbimport hashlibclass 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): # 建立對象:調用connect()方法 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() # fetchone() : # 返回單個的元組,也就是一條記錄(row),如果沒有結果 # 則返回 # None # fetchall() : # 返回多個元組,即返回多個記錄(rows), 如果沒有結果 # 則返回() # 需要註明:在MySQL中是NULL,而在Python中則是None 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() # 建立對象:調用Connection對象的cursor() 方法 # 執行語句,返回受影響的行數: execute(operation[, parameters]) count = self.cursor.execute(sql, params) self.conn.commit() self.close() except Exception as e: print e return count
mysql封裝類
# encoding=utf-8from MysqlHelper import MysqlHelperfrom hashlib import sha1def main(): sqlhelper = MysqlHelper(‘127.0.0.1‘, 3306, ‘student‘, ‘root‘, ‘root‘) # 使用者登入 sname = raw_input("請輸入使用者名稱:") spwd = raw_input("請輸入密碼:") # - update(arg):根據參數來更新hash對象, # 多個update調用相當於把所有參數串連起來的單個update調用 # - digest():返回hash字串 # - hexdigest():返回hash字串,16進位 # - copy():返回一個clone對象 s1 = sha1() s1.update(spwd) spwdSha1 = s1.hexdigest() sql = "select upwd from users where uname=%s" params = [sname] userinfo = sqlhelper.get_one(sql, params) if userinfo == None: print ‘使用者名稱錯誤‘ elif userinfo[0] == spwdSha1: print ‘登入成功‘ else: print ‘密碼錯誤‘if __name__ == ‘__main__‘: main()登入
MySQL與Python互動