5.Python操作MySQL,三層架構(gòu),Socket網(wǎng)絡(luò)編程-創(chuàng)新互聯(lián)

Python操作MySQL

創(chuàng)新互聯(lián)建站于2013年創(chuàng)立,先為海北州等服務(wù)建站,海北州等地企業(yè),進行企業(yè)商務(wù)咨詢服務(wù)。為海北州企業(yè)網(wǎng)站制作PC+手機+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。

- MySQL之查詢操作

- MySQL之插入數(shù)據(jù)

- MySQL之批量插入數(shù)據(jù)

- MySQL之刪除數(shù)據(jù)

- MySQL之更新數(shù)據(jù)庫

- MySQL之事務(wù)

- MySQL之批量獲取字典類型數(shù)據(jù)

- MySQL之fetchone

- MySQL之獲取自增ID

三層架構(gòu)(程序分成三種架構(gòu))

- 三層架構(gòu)之公共層

- 三層架構(gòu)之model層

- 三層架構(gòu)之配置文件

Socket網(wǎng)絡(luò)編程

【Python操作MySQL】

準備工作:

Windows下載鏈接,Python操作MySQL模塊:

http://pan.baidu.com/s/1o7JuMgU

提示:Windows安裝了mysql模塊后,因為我用的是Eclipse,所以我還要在Eclipse下做一下設(shè)置,如下:

在Eclipse菜單欄上點擊Windows->Preferences->PyDev-Interpreter-Python->Forced Builtins->New->MySQLdb->ok->Apply,必要時重啟Eclipse

Linux直接安裝Python操作MySQL模塊 yum -y install python-mysqldb

建表語句

create table students     (         id int  not null auto_increment primary key,         name char(8) not null,         sex char(4) not null,         age tinyint unsigned not null,         tel char(13) null default "-"     );

插入數(shù)據(jù):

insert into students(name,sex,age,tel) values('wsyht','man',20,'1319')

數(shù)據(jù)庫和表

mysql> select database(); +------------+ | database() | +------------+ | wsyht      | +------------+ 1 row in set (0.00 sec) mysql> select *from students; +----+---------+-----+-----+---------+ | id | name    | sex | age | tel     | +----+---------+-----+-----+---------+ |  2 | wsyht   | man |  22 | 1231313 | |  3 | jack    | man |  23 | 12313   | |  4 | jenkins | man |  25 | 123     | |  5 | peter   | man |  23 | 123     | |  6 | wsyht90 | man |  23 | 123     | |  8 | wsyht11 | man |  26 | 12345   | |  9 | wsyht12 | man |  26 | 12345   | | 10 | wsyht1  | man |  26 | 12345   | | 11 | wsyht2  | man |  26 | 12345   | +----+---------+-----+-----+---------+ 9 rows in set (0.00 sec)

1)MySQL之查詢操作

import MySQLdb   #必須在導入MySQLdb模塊之前,要先裝python操作mysql模塊

#創(chuàng)建連接

conn = MySQLdb.connect(host='192.168.1.113',user='root',passwd='123456',db='wsyht') #這里可以理解為打開門的鑰匙  cur = conn.cursor()  #這里可以理解為伸出手,這里可以理解為伸出手,獲取表數(shù)據(jù)

#數(shù)據(jù)查詢操作

reCount = cur.execute('select * from students') #然后執(zhí)行動作,只是查詢影響了多少行,并不是查詢相關(guān)表的數(shù)據(jù) data = cur.fetchall()  #把select查詢影響到的行的數(shù)據(jù)全拿出來

#關(guān)閉連接

cur.close()   #收回手 conn.close()  #關(guān)門

#輸出信息

print reCount #輸出查詢影響到的行數(shù) print data    #輸出查詢影響到的行的數(shù)據(jù)

2)MySQL之插入數(shù)據(jù)

import MySQLdb

#創(chuàng)建連接

conn = MySQLdb.connect(host='192.168.1.113',user='root',passwd='123456',db='wsyht') #這里可以理解為打開門的鑰匙  cur = conn.cursor()  #這里可以理解為伸出手,這里可以理解為伸出手,獲取表數(shù)據(jù)

#數(shù)據(jù)插入操作

sql = "insert into students(id,name,sex,age,tel) values(%s,%s,%s,%s,%s)" #不管什么類型,占位符都是給%s,五個占位符,就給五個%s params = ('6','peter','man','23','123')  #如果這里id設(shè)了自增,那么這排第一位和上面一排第一位id可以不用寫 reCount = cur.execute(sql,params)  #插入數(shù)據(jù)    conn.commit()  #提交數(shù)據(jù),insert,update,delete都要加commit,而select則不用

#關(guān)閉連接

cur.close()   #收回手 conn.close()  #關(guān)門 print reCount #輸出影響到的行數(shù)

3)MySQL之批量插入數(shù)據(jù)

import MySQLdb   #必入MySQLdb模塊之前,要先裝python操作mysql模塊

#創(chuàng)建連接

conn = MySQLdb.connect(host='192.168.1.113',user='root',passwd='123456',db='wsyht') #這里可以理解為打開門的鑰匙 cur = conn.cursor()  #這里可以理解為伸出手,這里可以理解為伸出手,獲取表數(shù)據(jù)

#批量插入數(shù)據(jù)操作

li = [     ('wsyht11','man','26','12345'),     ('wsyht12','man','26','12345'), ] #sql = 'insert into students(name,sex,age,tel) values(%s,%s,%s,%s)' #reCount = cur.executemany(sql,li)  reCount = cur.executemany('insert into students(name,sex,age,tel) values(%s,%s,%s,%s)',li)  #刪除數(shù)據(jù) conn.commit()  #提交數(shù)據(jù),insert,update,delete都要加commit,而select則不用

#關(guān)閉連接

cur.close()   #收回手 conn.close()  #關(guān)門 print reCount #輸出影響到的行數(shù)

4)MySQL之刪除數(shù)據(jù)庫

import MySQLdb   #必入MySQLdb模塊之前,要先裝python操作mysql模塊

#創(chuàng)建連接

conn = MySQLdb.connect(host='192.168.1.113',user='root',passwd='123456',db='wsyht') #這里可以理解為打開門的鑰匙 cur = conn.cursor()  #這里可以理解為伸出手,這里可以理解為伸出手,獲取表數(shù)據(jù)

#數(shù)據(jù)刪除操作

sql = "delete from students where id=%s" #不管什么類型,占位符都是給%s, params = (7,)  #把%s需要刪除的數(shù)據(jù)內(nèi)容添加到params變量就可以了,如果是字符,則需要用單引號引起來如:('n1',) reCount = cur.execute(sql,params)  #刪除數(shù)據(jù) conn.commit()  #提交數(shù)據(jù),insert,update,delete都要加commit,而select則不用

#關(guān)閉連接

cur.close()   #收回手 conn.close()  #關(guān)門 print reCount #輸出影響到的行數(shù)

5)MySQL之更新數(shù)據(jù)庫

import MySQLdb   #必入MySQLdb模塊之前,要先裝python操作mysql模塊

#創(chuàng)建連接

conn = MySQLdb.connect(host='192.168.1.113',user='root',passwd='123456',db='wsyht') #這里可以理解為打開門的鑰匙 cur = conn.cursor()  #這里可以理解為伸出手,這里可以理解為伸出手,獲取表數(shù)據(jù)

#數(shù)據(jù)更新操作

sql = "update students set name=%s where id=6" #不管什么類型,占位符都是給%s, params = ('wsyht90')  #把id為6那一行數(shù)據(jù)中的name內(nèi)容改為wsyht90 reCount = cur.execute(sql,params)  #更新數(shù)據(jù) conn.commit()  #提交數(shù)據(jù),insert,update,delete都要加commit,而select則不用

#關(guān)閉連接

cur.close()   #收回手 conn.close()  #關(guān)門 print reCount #輸出影響到的行數(shù)

6)事務(wù),要所有提交成功才會執(zhí)行成功

mysql> select *from students; +----+---------+-----+-----+---------+ | id | name    | sex | age | tel     | +----+---------+-----+-----+---------+ |  2 | wsyht   | man |  22 | 1231313 | |  3 | jack    | man |  23 | 12313   |

import MySQLdb   #必入MySQLdb模塊之前,要先裝python操作mysql模塊 conn = MySQLdb.connect(host='192.168.1.113',user='root',passwd='123456',db='wsyht') #這里可以理解為打開門的鑰匙 cur = conn.cursor()  #這里可以理解為伸出手 sql = "update students set age=%s where id=2" params = (0) reCount = cur.execute(sql,params) sql = "update students set age=%s where id=3" params = (46) reCount = cur.execute(sql,params) conn.commit() cur.close()   #收回手 conn.close()  #關(guān)門 print reCount #輸出影響到的行數(shù)

mysql> select *from students; +----+---------+-----+-----+---------+ | id | name    | sex | age | tel     | +----+---------+-----+-----+---------+ |  2 | wsyht   | man |   0 | 1231313 | |  3 | jack    | man |  46 | 12313   |

7)MySQL之批量獲取字典類型數(shù)據(jù)

import MySQLdb   #必入MySQLdb模塊之前,要先裝python操作mysql模塊

#創(chuàng)建鏈接

conn = MySQLdb.connect(host='192.168.1.113',user='root',passwd='123456',db='wsyht') #這里可以理解為打開門的鑰匙  #cur = conn.cursor()  #這里可以理解為伸出手,這里可以理解為伸出手,獲取表數(shù)據(jù) cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)  #以字典類型獲取數(shù)據(jù),也就是獲取表的列名和列的數(shù)據(jù)

#數(shù)據(jù)操作

reCount = cur.execute('select * from students') #然后執(zhí)行動作,只是查詢影響了多少行,并不是查詢相關(guān)表的數(shù)據(jù) data = cur.fetchall()  #把select查詢影響到的行的數(shù)據(jù)全拿出來

#關(guān)閉連接

cur.close()   #收回手 conn.close()  #關(guān)門 print reCount #輸出查詢影響到的行數(shù) print data    #輸出查詢影響到的行的數(shù)據(jù)

8)MySQL之fetchone

import MySQLdb conn = MySQLdb.connect(host='192.168.1.113',user='root',passwd='123456',db='wsyht') #這里可以理解為打開門的鑰匙  cur = conn.cursor()  #這里可以理解為伸出手,獲取表數(shù)據(jù) #cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)

#數(shù)據(jù)操作

reCount = cur.execute('select * from students') #然后執(zhí)行動作,只是查詢影響了多少行,并不是查詢相關(guān)表的數(shù)據(jù) data = cur.fetchone()  #只輸出取到數(shù)據(jù)的第一行 print data    #輸出查詢影響到的行的數(shù)據(jù) #cur.scroll(0,mode='absolute')   #覺對模式,往上走一層,從重輸出 data = cur.fetchone()  #輸出取到數(shù)據(jù)的第二行 print data    #輸出查詢影響到的行的數(shù)據(jù) cur.scroll(-1,mode='relative')  #相對模式,往上走一層,從重新輸出 data = cur.fetchone()  #輸出取到數(shù)據(jù)的第三行 cur.close() conn.close() print data    #輸出查詢影響到的行的數(shù)據(jù)

9)MySQL之獲取自增ID

#可看到下表ID是12,然后我插入三次數(shù)據(jù)就會變成十五,代碼如下所示

mysql> select *from students; +----+-------+-----+-----+-------+ | id | name  | sex | age | tel   | +----+-------+-----+-----+-------+ |  3 | jack  | man |  22 | 12313 | | 12 | peter | man |  23 | 123   | +----+-------+-----+-----+-------+

import MySQLdb conn = MySQLdb.connect(host='192.168.1.113',user='root',passwd='123456',db='wsyht') #這里可以理解為打開門的鑰匙  cur = conn.cursor()  #這里可以理解為伸出手,獲取表數(shù)據(jù)

#數(shù)據(jù)操作

sql = "insert into students(name,sex,age,tel) values(%s,%s,%s,%s)" #不管什么類型,占位符都是給%s,四個占位符,就給四個%s params = ('peter','man','23','123')   reCount = cur.execute(sql,params)  #插入數(shù)據(jù)    conn.commit()  #提交數(shù)據(jù),insert,update,delete都要加commit,而select則不用 new_id = cur.lastrowid   #自動自增ID print new_id #輸出新的ID #關(guān)閉連接 cur.close()   #收回手 conn.close()  #關(guān)門

#再次查看數(shù)據(jù)表

mysql> select *from students; +----+-------+-----+-----+-------+ | id | name  | sex | age | tel   | +----+-------+-----+-----+-------+ |  3 | jack  | man |  22 | 12313 | | 12 | peter | man |  23 | 123   | | 13 | peter | man |  23 | 123   | | 14 | peter | man |  23 | 123   | | 15 | peter | man |  23 | 123   | +----+-------+-----+-----+-------+

【三層架構(gòu)】 (程序分成三種架構(gòu))

數(shù)據(jù)訪問層

業(yè)務(wù)處理層

表示層,UI層

08day10  #工程(項目)   - model     #(包)數(shù)據(jù)庫里有幾張表,這里就建幾個文件,并且跟數(shù)據(jù)庫的名要一一對應,也就是要對什么表操作就建什么名字的模塊文件     - __init__.py     - students.py   #有一個表叫students,可以調(diào)用sql_helper模塊文件對students表做增刪改查操作,公共配置配寫在sql_helper,增刪改查寫在students,最后由admin去做執(zhí)行   - utility   #(包)公共層,這里寫公共的一些功能,比如說對數(shù)據(jù)庫的操作,又比如說你要用網(wǎng)絡(luò)服務(wù)的時候,你需要請求哪個地址,那你可以再為他建一個單獨文件,統(tǒng)一操作,所有一類的都通過我去執(zhí)行,如下     - __init__.py     - sql_helper.py   #數(shù)據(jù)庫的公共配置操作   - conf.py   #(模塊)這里面放配置文件,比如:要連接的數(shù)據(jù)庫或者要連接的接口把他的URL放在這里   - index.py  #(模塊)主文件,程序進來首先執(zhí)行的文件,index再起觸發(fā)其他模塊的其他類,或其它類里的方法

1)三層架構(gòu)之公共層

cat sql_helper.py #!/usr/bin/env python #coding:utf-8 import MySQLdb import conf class MySQLHelper(object):     def __init__(self):         self.__conn_dict = conf.conf_dict     def Get_Dict(self,sql,params):         conn = MySQLdb.connect(host='192.168.1.113',user='root',passwd='123456',db='wsyht')         cur = conn.cursor()         reCount = cur.execute(sql,params)         data = cur.fetchall()         cur.close()         conn.close()         return data    #返回值給調(diào)用方     def Get_One(self,sql,params):         conn = MySQLdb.connect(**self.__conn_dict)  #兩個*以字典方式傳多個值,一個*以列表方式傳值,傳多個值         cur = conn.cursor()         reCounts = cur.execute(sql,params)         data = cur.fetchone()         cur.close()         conn.close()         return data    #返回值給調(diào)用方 '''   #注意:調(diào)用的話不是直接寫在這個文件調(diào)用,這不過是為了演示 helper = MySQLHelper() sql = "select *from students where id > %s" params = (15) one_data = helper.Get_one(sql, params) dict_data = helper.Get_Dict(sql, params) print one_data print dict_data '''

2)三層架構(gòu)之model層

cat students.py #!/usr/bin/env python #coding:utf-8 from  utility.sql_helper import MySQLHelper  #把類導入進來 class Students(object):     def __init__(self):         self.__helper = MySQLHelper()    #面向?qū)ο褓x值給私有字段     def Get_One(self,id):         sql = "select *from students where id = %s"         params = (id)         return self.__helper.Get_One(sql,params)     def CheckValidate(self,username,password):         sql = "select * from students where name = %s and password = %s"         params = (username,password)         return self.__helper.Get_One(sql,params) 3)三層架構(gòu)之配置文件  conf一般與utility這一層進行相應的設(shè)置 #!/usr/bin/env python #coding:utf-8 #以字典方式傳值,第一排和第二排勻是用字典方式傳值,任選其一即可,以后要改IP啥的來這里改即可 conf_dict = dict(host='192.168.1.113',user='root',passwd='123456',db='wsyht') #conf_dict = {'host':'192.168.1.113','user':'root','passwd':'123456','db':'wsyht'}

#主程序執(zhí)行文件

cat index.py #!/usr/bin/env python #coding:utf-8 from model.students import Students def main():     user = raw_input('username:')     pwd = raw_input('password:')     students = Students()     result = students.CheckValidate(user,pwd)     if not result:         print '你輸入的用戶名或密碼有誤'     else:         print '歡迎登陸后臺管理頁面' if __name__ == '__main__':     main()

#wsyht庫下的students表

mysql> select *from students; +----+---------+-----+-----+----------+ | id | name    | sex | age | password | +----+---------+-----+-----+----------+ |  1 | wsyht   | man |  18 | 123456   | |  2 | jenkins | man |  20 | 13579    | +----+---------+-----+-----+----------+

執(zhí)行順序總結(jié):     -->1、調(diào)用配置文件

主程序(index文件)--> model層(students表文件)--> 公共層(sql_helper數(shù)據(jù)庫公共操作文件)

    -->2、調(diào)用數(shù)據(jù)庫

寫法總結(jié): 寫法則是按執(zhí)行順序從后往上

1、先寫公共層

2、寫model層

3、寫主程序文件

4、寫配置文件

【Socket網(wǎng)絡(luò)編程】

- main 包    - client.py     - server.py  示例1: #!/usr/bin/env Python #coding:utf-8 import socket def handle_request(client):       buf = client.recv(1024)   #客戶端接收服務(wù)端數(shù)據(jù),緩存區(qū)1024字節(jié),最多只能拿1024字節(jié)     client.send("HTTP/1.1 200 OK\r\n\r\n")  #服務(wù)端發(fā)送信息     client.send("Hello,World!123")   #服務(wù)端發(fā)送信息     print buf def main():     sock = socket.socket()         #建立socket對像     sock.bind(('localhost',5821))  #監(jiān)聽本地8080端口     sock.listen(5)           #允許建立的大連接數(shù)     while True:         connection, address = sock.accept()    #阻塞直接有客戶端請求,connectin就是客戶端的socket對像,address代表客戶端的地址         handle_request(connection)         connection.close()      if __name__ == '__main__':     main() #瀏覽器訪問測試 http://localhost:5821

示例2:

main    #包   - init.py   - server.py   - client.py 服務(wù)端腳本 cat server.py  #!/usr/bin/env python #coding:utf-8 import  socket sk = socket.socket()   #調(diào)用socket的這個類對像,創(chuàng)建對像 ip_port = ('127.0.0.1',873) sk.bind(ip_port)       #監(jiān)聽服務(wù)器的IP和端口 sk.listen(5)           #允許的大接數(shù)為5 while True:            #創(chuàng)建一個死循環(huán),讓他不停的接收用戶發(fā)過來的請求     conn,address = sk.accept()       #阻塞等待直到有客戶端連接,conn就是客戶端的socket對像,address代表客戶端的地址     conn.send('Hello,Wo2ld!')               #向客戶端發(fā)送數(shù)據(jù)     conn.close()                     #對客戶端關(guān)閉連接

客戶端腳本

cat client.py #!/usr/bin/env python #coding:utf-8 import socket client = socket.socket()              #創(chuàng)建客戶端socket ip_port = ('127.0.0.1',873)            client.connect(ip_port)              #連接服務(wù)端 data = client.recv(1024)              #接收服務(wù)端數(shù)據(jù) print  data

執(zhí)行腳本:先執(zhí)行服務(wù)端腳本,再執(zhí)行客戶端腳本

socket服務(wù)端執(zhí)行步驟:

1、創(chuàng)建socket對像

2、監(jiān)聽服務(wù)器IP和端口

3、設(shè)置大連接數(shù)

4、阻塞等待直到有客戶端連接

5、發(fā)送數(shù)據(jù)

6、關(guān)閉連接

socket客戶端執(zhí)行步驟

1、創(chuàng)建socket對像

2、與服務(wù)器端建立連接

3、請求數(shù)據(jù)

Socket客戶端與服務(wù)端的交互示例:

-

main 包    - client.py     - server.py  服務(wù)器端演示: #!/usr/bin/env Python #coding:utf-8 import socket sk = socket.socket() ip_port = ('127.0.0.1',995) sk.bind(ip_port) sk.listen(5)     #阻塞數(shù)量 while True:     conn,address = sk.accept()     conn.send('hello')     print '新用戶進入系統(tǒng)'     print 'server:hello'     flag = True         while flag:             data = conn.recv(1024)              #接收客戶端數(shù)據(jù)             if data == 'exit':                 flag = False                 print '對方已退出系統(tǒng)'                 break             print 'client:',data             inp = raw_input('server:')             conn.send(inp)         conn.close()

客戶端演示:

#!/usr/bin/env Python #coding:utf-8 import socket client = socket.socket() ip_port = ('127.0.0.1',995) client.connect(ip_port) while True:     data = client.recv(1024)          #接收服務(wù)端數(shù)據(jù)     print 'server:',data     inp = raw_input('client:')     client.send(inp)     if inp == 'exit':         break

#異步多線程服務(wù)端

cat server.py #!/usr/bin/env Python #coding:utf-8 import SocketServer class MyServer(SocketServer.BaseRequestHandler):     def setup(self):         pass def handle(self):     conn = self.request     conn.send('hello')     print '新用戶進入系統(tǒng)'     print 'server:hello'     flag = True     while flag:         data = conn.recv(1024)         if data == 'exit':             flag = False             print '對方已退出系統(tǒng)'             break         print 'client:',data         inp = raw_input('server:')         conn.send(inp)     conn.close() def  finish(self):     pass if __name__ == '__main__':     server = SocketServer.ThreadingTCPServer(('127.0.0.1',995),MyServer)     server.serve_forever()

#客戶端

cat client.py #!/usr/bin/env Python #coding:utf-8 import socket client = socket.socket() ip_port = ('127.0.0.1',995) client.connect(ip_port) while True:     data = client.recv(1024)     print 'server:',data     inp = raw_input('client:')     client.send(inp)     if inp == 'exit':         break

#可以拷貝多一個client.py文件出來,然后,先執(zhí)行服務(wù)端程序,再執(zhí)行兩個客戶端文件,就可以實現(xiàn)異步處理兩個對話,也就是異步多線程處理

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)cdcxhl.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。

當前題目:5.Python操作MySQL,三層架構(gòu),Socket網(wǎng)絡(luò)編程-創(chuàng)新互聯(lián)
本文路徑:http://www.muchs.cn/article20/cdjico.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站導航品牌網(wǎng)站建設(shè)、網(wǎng)站建設(shè)、營銷型網(wǎng)站建設(shè)、網(wǎng)站制作、服務(wù)器托管

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

搜索引擎優(yōu)化