基於python中的mysql管理,多線程和soecket

pyhton中的mysql

MySQL是一個關係型數據庫管理系統,由瑞典MySQL AB 公司開發,目前屬於 Oracle 旗下產品。MySQL 是最流行的關係型數據庫管理系統之一,在 WEB 應用方面,MySQL是最好的 RDBMS (Relational Database Management System,關係數據庫管理系統) 應用軟件。
MySQL是一種關係數據庫管理系統,關係數據庫將數據保存在不同的表中,而不是將所有數據放在一個大倉庫內,這樣就增加了速度並提高了靈活性。
MySQL所使用的 SQL 語言是用於訪問數據庫的最常用標準化語言。MySQL 軟件採用了雙授權政策,分爲社區版和商業版,由於其體積小、速度快、總體擁有成本低,尤其是開放源碼這一特點,一般中小型網站的開發都選擇 MySQL 作爲網站數據庫。
由於其社區版的性能卓越,搭配 PHP 和 Apache 可組成良好的開發環境
管理數據庫分以下幾步走:
在進行數據庫管理之前需要把python中的MYSQLdb數據包導入python中
具體操作如下:

yum install  mariadb-server -y  安裝
systemctl start mariadb
systemctl stop firewalld
mysql_secure_installation  #安裝設置,只允許本機超級用戶加密登陸
New password:
Re-enter new password:
Reloading privilege tables..
Remove anonymous users? [Y/n] y
Disallow root login remotely? [Y/n] y
Remove test database and access to it? [Y/n] y
Reload privilege tables now? [Y/n] y
mysql -uroot -predhat #用root登陸,密碼爲redhat,不安全,其他用戶可以看到超級用戶密碼
mysql -uroot -p #超級用戶加密後登錄
yum search MySQL-python
yum install MySQL-python.x86_64 -y  安裝服務
pip install Mysql-Python  建立連接在網上下載三方軟件

網頁管理數據庫

 yum install php httpd -y
    systemctl start httpd
    systemctl stop firewalld
    cd /var/www/html/
    ls
    get phpMyAdmin-3.4.0-all-languages.tar.bz2
    ls
    tar jxf phpMyAdmin-3.4.0-all-languages.tar.bz2
    ls
    rm -f phpMyAdmin-3.4.0-all-languages.tar.bz2
    ls
    mv phpMyAdmin-3.4.0-all-languages/ mysqladmin
    ls
    cd mysqladmin/
    ls
    cp config.sample.inc.php config.inc.php
    cd ..
    yum install php-mysql.x86_64 -y #該安裝包是爲了在php中添加mysql功能
    systemctl restart httpd


在數據庫中新建一個庫:這裏寫圖片描述

import MySQLdb
# 打開門
conn = MySQLdb.connect(host='127.0.0.1',user = 'root',passwd='redhat',db='python')

# 伸出手
cur = conn.cursor()

# 拿東西
recont = cur.execute('select * from userInfo')

# 把手伸回來
cur.close()

# 把門關上
conn.close()

# 打印返回結果
print recont

返回結果爲操作了多少行

1 >查看並輸出數據庫指定表中的數據:

import MySQLdb
# 打開門
conn = MySQLdb.connect(host='127.0.0.1',user = 'root',passwd='redhat',db='python')

# 伸出手
# 創建了一隻手
cur = conn.cursor()

# 拿東西
# 這個操作影響了多少行數(有多少行被操作了) execute 執行
recont = cur.execute('select * from userInfo')
# 看東西  fetchall 取物
data = cur.fetchall()
# 把手伸回來
cur.close()

# 把門關上
conn.close()

print recont
print data

1.1>以字典的方式查看並輸出數據庫中的內容:

# 打開門
conn = MySQLdb.connect(host='127.0.0.1',user = 'root',passwd='redhat',db='python')

# 伸出手
# 創建了一隻手 cursor 指針
# cur = conn.cursor()
**cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)**
# 拿東西
# 這個操作影響了多少行數(有多少行被操作了) execute 執行
recont = cur.execute('select * from userInfo')
# 看東西  fetchall 取物
data = cur.fetchall()
# 把手伸回來
cur.close()

# 把門關上
conn.close()

print recont
print data

2>python中的mysql增

import MySQLdb
# 打開門
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='redhat',db='python')
# 伸出手
cur = conn.cursor()
# 操作數據
sql = 'insert into new_table (name,age,Feature)values(%s,%s,%s)'
params = ('Tom','12','westos')
recount = cur.execute(sql,params)
recont = cur.execute('select * from new_table')
# 看東西  fetchall 取物
data = cur.fetchall()

# 提交
conn.commit()
# 把手伸回來
cur.close()
# 把門關上
conn.close()
print recount
print data

3>python中的mysql改

import MySQLdb
# 打開門
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='redhat',db='python')
# 伸出手
cur = conn.cursor()
# 操作數據
sql = 'update new_table set age= %s where name=%s'
# 元組中如果第一個數字後面不加','會被看作int整形,在元組中所有數據都是字符串
params = (1,'Tom',) # ('更改後的內容',where,)
recount = cur.execute(sql,params)
# 拿東西
recont = cur.execute('select * from new_table')
# 看東西  fetchall 取物
data = cur.fetchall()
# 提交
conn.commit()
# 把手伸回來
cur.close()
# 把門關上
conn.close()
print recount
print data

4>python中的mysql刪

import MySQLdb
# 打開門
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='redhat',db='python')
# 伸出手
cur = conn.cursor()
# 操作數據
sql = 'delete from new_table where name = %s '
# 元組中如果第一個數字後面不加','會被看作int整形,在元組中所有數據都是字符串
params = ('Tom',)
recount = cur.execute(sql,params)
# 提交
conn.commit()
# 把手伸回來
cur.close()
# 把門關上
conn.close()
print recount

5>python中的提交和回滾

在數據庫裏提交事物操作
如果沒有提交,那麼系統不會接收到用戶操作,結果也不會改變
交互式假設A給B轉賬,那麼A的戶頭就會減少,B的戶頭會增加
如何實現:

import MySQLdb
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='redhat',db='python')
cur = conn.cursor()

sql = 'update count set money = %s where id = 1'
params = ('100',)
recount = cur.execute(sql,params)
conn.commit()

sql = 'update count set money = %s where id = 2'
params = ('0',)
recount = cur.execute(sql,params)
conn.commit()

轉賬之前

轉賬之後

6>在mysql中插入多條數據

import MySQLdb
# 打開門
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='redhat',db='python')
# 伸出手
cur = conn.cursor()
# 操作數據
sql = 'insert into new_table (name,age,Feature)values(%s,%s,%s)'

params = [('Lily',2,'Teacher'),
          ('Oldlee',3,'Pang'),
          ('Yuhan',4,'Mei')]

# cur.executemany 多行執行
recount = cur.executemany(sql, params)
# 測試查看修改是否成功
recont = cur.execute('select * from new_table')
data = cur.fetchall()
# 提交
conn.commit()
# 把手伸回來
cur.close()
# 把門關上
conn.close()
print recount
print data



2 多線程

線程和進程的區別:

1.進程:是執行中一段程序,即一旦程序被載入到內存中並準備執行,它就是一個進程。進程是表示資源分配的的基本概念,又是調度運行的基本單位,是系統中的併發執行的單位。

線程:單個進程中執行中每個任務就是一個線程。線程是進程中執行運算的最小單位。

2.一個線程只能屬於一個進程,但是一個進程可以擁有多個線程。多線程處理就是允許一個進程中在同一時刻執行多個任務。

3.線程是一種輕量級的進程,與進程相比,線程給操作系統帶來側創建、維護、和管理的負擔要輕,意味着線程的代價或開銷比較小。

4.線程沒有地址空間,線程包含在進程的地址空間中。線程上下文只包含一個堆棧、一個寄存器、一個優先權,線程文本包含在他的進程 的文本片段中,進程擁有的所有資源都屬於線程。所有的線程共享進程的內存和資源。

線程是操作系統能夠進行運算調度的最小單位(程序執行流的最小單位)
它被包含在進程之中,是進程中的實際運作單位.一個進程中可以併發多個線程
每條西那成並行執行不同的任務
(線程是進程中的一個實體,是被系統獨立調度和分派的基本單元)
每一個進程啓動時都會最先產生一個線程,即主線程
然後主線程會再創建其他的子線程

多線程能幹什麼?

import threading
from time import ctime, sleep


def music(a):
    for i in range(2):
        print 'I was listening to %s. %s \n' % (a, ctime())
        sleep(1)


def movie(b):
    for i in range(2):
        print 'I was watching to %s. %s \n' % (b, ctime())
        sleep(5)


# music('故鄉')
# movie('我不是藥神')
t1 = threading.Thread(target=music,args=('故鄉',))
t1.start()
t2 = threading.Thread(target=movie,args=('我不是藥神',))
t2.start()
print 'all over %s' %ctime()

可以看到music和movie是同時進行的,他們是兩個互不干擾的線程,主線程不等待分線程的執行

線程之間建立關係
from threading import Thread
def Foo(arg):
    print arg

print 'before'
# 線程之間建立關係
t1 = Thread(target=Foo,args=(1,))
t1.start()
print 'after'

getName 獲取分線程名稱

這個程序中主線程等待分線程執行完畢才執行

from threading import Thread
def Foo(arg):
    print arg

print 'before'


# 線程之間建立關係
t1 = Thread(target=Foo,args=(1,))
t1.start()
print t1.getName()

t2 = Thread(target=Foo,args=(2,))
t2.start()
print t2.getName()

print 'after'

主線程不等待分線程執行結束

from threading import Thread
import time
def Foo():
    for item in range(8):
        print item
        time.sleep(1)
print 'before'

# 線程之間建立關係
t1 = Thread(target=Foo)
t1.setDaemon(True)
t1.start()
print 'after'
time.sleep(100)

import threading
import time


def Foo():
    for item in range(10):
        print item
        time.sleep(1)


print 'before'
t1 = threading.Thread(target=Foo)
t1.start()
# 主線程到join()就不往下走了,直到子線程執行完畢
t1.join(5)
print 'after'
# 主線程只等分線程5秒,然後就執行自己的程序


買包子事件,消費者購買包子時間短,生產者生產包子時間長,當包子不能滿足消費者時,
就會提醒生產者沒有包子了,生產者就會製作包子滿足消費者,這樣程序就不會中斷,用異常來處理

import threading
import Queue
import time
import random

def Producer(name,que):
    while True:
        que.put('baozi')
        print '%s:Made a baobzi..======' % name
        time.sleep(random.randrange(5))
def Consumer(name,que):
    while True:
        try:
            que.get_nowait()
            print '%s:Got a baobao..' % name
        except Exception:
            print '沒有包子了'
        time.sleep(random.randrange(3))
# 創建隊列
q = Queue.Queue()

p1 = threading.Thread(target=Producer,args=['chef1',q] )
p2 = threading.Thread(target=Producer,args=['chef2',q] )

p1.start()
p2.start()

c1 = threading.Thread(target=Consumer,args=['tom',q] )
c2 = threading.Thread(target=Consumer,args=['harry',q] )

c1.start()
c2.start()


當還有三個包子時,就會提醒生產者生產包子

def Producer(name, que):
    while True:
        if que.qsize() < 3:
            que.put('baozi')
            print '%s:Made a baobzi..======' % name
        else:
            print '還有三個包子'
        time.sleep(random.randrange(5))


def Consumer(name, que):
    while True:
        try:
            que.get_nowait()
            print '%s:Got a baobao..' % name
        except Exception:
            print '沒有包子了'
        time.sleep(random.randrange(3))


# 創建隊列
q = Queue.Queue()

p1 = threading.Thread(target=Producer, args=['chef1', q])
p2 = threading.Thread(target=Producer, args=['chef2', q])

p1.start()
p2.start()

c1 = threading.Thread(target=Consumer, args=['tom', q])
c2 = threading.Thread(target=Consumer, args=['harry', q])

c1.start()
c2.start()


計數從1-500

import time                                          
import threading                                     
num = 0                                              
def run(n):                                          
    time.sleep(1)                                    
    global num                                       
    # 線程鎖                                            
    lock.acquire()                                   
    num += 1                                         
    print '%s\n' %num                                
    lock.release()                                   
lock = threading.Lock()                              
for i in range(500):                                 
    t = threading.Thread(target=run,args=(i,))       
    t.start()                                        

事物驅動:

import threading
import time

def Producer():
    print 'chef:等人來買包子'
    #收到了消費者的event.set 也就是把這個flag改爲了true,但是我們的包子並沒有做好
    event.wait()
    #此時應該將flag的值改回去
    event.clear()
    print 'chef:someone is coming for 包子'
    print 'chef:making a 包子 for someone'
    time.sleep(5)
    # 告訴人家包子做好了
    print '你的包子好了~'
    event.set()

def Consumer():
    print 'tom:去買包子'
    # 告訴人家我來了
    event.set()
    time.sleep(2)
    print 'tom:waiting for 包子 to be ready'
    event.wait()
    print '哎呀~真好喫'

event = threading.Event()

p1 = threading.Thread(target=Producer)
c1 = threading.Thread(target=Consumer)
p1.start()
c1.start()

異步:

import threading
import time

def Producer():
    print 'chef:等人來買包子'
    # 收到了消費者的event.set 也就是把這個flag改爲了true,但是我們的包子並沒有做好
    event.wait()
    # 此時應該將flag的值改回去
    event.clear()
    print 'chef:someone is coming for 包子'
    print 'chef:making a 包子 for someone'
    time.sleep(5)
    # 告訴人家包子做好了
    print '你的包子好了~'
    event.set()

def Consumer():
    print 'tom:去買包子'
    # 告訴人家我來了
    event.set()
    time.sleep(2)
    print 'tom:waiting for 包子 to be ready'
    # 我在不斷檢測,但我已經不阻塞了
    while True:
        if event.is_set():
            print 'Thanks~'
            break
        else:
            print '怎麼還沒好呀~'
            # 模擬正在做自己的事情
            time.sleep(1)
event = threading.Event()

p1 = threading.Thread(target=Producer)
c1 = threading.Thread(target=Consumer)
p1.start()
c1.start()

Socket

什麼是socket?

網絡上的兩個程序通過一個雙向的通信連接實現數據的交換,這個連接的一端稱爲一個socket
所謂socket通常也稱作“套接字”,用於描述IP地址和端口,是一個通信鏈的句柄,應用程序通常通過“套接字”向網絡發出請求或應答網絡請求
socket起源於Uinx,而Unix/Linux基本哲學之一就是“一切皆文件”,都可以用“打開open–>讀寫write/read–>關閉close”模式來操作,socket就是該模式的一個實現,socket即是一種特殊的文件,一些socket函數就是對其進行的操作(讀/寫 IO,打開,關閉)
Socket的英文原義是“孔”或“插座”。作爲BSD UNIX的進程通信機制,取後一種意思。通常也稱作”套接字”,用於描述IP地址和端口,是一個通信鏈的句柄,可以用來實現不同虛擬機或不同計算機之間的通信。在Internet上的主機一般運行了多個服務軟件,同時提供幾種服務。每種服務都打開一個Socket,並綁定到一個端口上,不同的端口對應於不同的服務。Socket正如其英文原義那樣,像一個多孔插座。一臺主機猶如佈滿各種插座的房間,每個插座有一個編號,有的插座提供220伏交流電,有的提供110伏交流電,有的則提供有線電視節目。 客戶軟件將插頭插到不同編號的插座,就可以得到不同的服務

例如:中國移動客服
對於移動來說:一直監聽一個號碼10086,當有電話進來後,就分配一個客服和客戶去溝通並處理請求
對於用戶:需要知道10086這個號碼,並需要打電話
建了一個服務端一個客戶端:
客戶端:

import socket

# 創建一個socket對象
client = socket.socket()

# 創建連接
ip_port = ('127.0.0.1', 2387)
client.connect(ip_port)

# 獲取數據
while True:
    data = client.recv(1024)
    print data
    # 發送數據
    inp = raw_input('client:')
    client.send(inp)
    if inp == 'exit':
        break
import socket
# 1.創建socket對象
sk = socket.socket()
# 2.綁定端口和ip
ip_port = ('127.0.0.1',2387)
sk.bind(ip_port)
# 3.最大連接數
sk.listen(5)

while True:
    # 獲取客戶端的ip和端口號
    conn,address = sk.accept()
    # conn = result[0]
    # address = result[1]
    # print result
    # print type(result) 元組型
    conn.send('hello')
    flag = True
    while flag:
        data = conn.recv(1024)
        print data
        if data == 'exit':
            flag = False
        conn.send('ouhayou')
    conn.close()

在服務端運行的過程中:在客戶端發出請求:

[kiosk@foundation30 socket]$ python client.py 
hello
client:nihao 
ouhayou
client:exit
[kiosk@foundation30 socket]$ pwd
/home/kiosk/PycharmProjects/python_08/socket

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