溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

從零開(kāi)始學(xué)Python-day7

發(fā)布時(shí)間:2020-06-19 14:28:47 來(lái)源:網(wǎng)絡(luò) 閱讀:451 作者:0leaves0 欄目:數(shù)據(jù)庫(kù)

python-Day7


學(xué)習(xí)要有定位,明確目標(biāo)地去學(xué)習(xí)。希望自己能堅(jiān)持下去,并有所收獲---leaves(ps月初有事耽誤計(jì)劃了,進(jìn)度落后計(jì)劃蠻多了,算了。不多想,復(fù)習(xí),學(xué)會(huì)才是硬道理,堅(jiān)持fighting!)


python06 -- python的pickle模塊以及mysql數(shù)據(jù)庫(kù)初始用



一、python的pickle模塊

1.1 pickle模塊的作用

    pickle是為了序列化/反序列化數(shù)據(jù)的,可以把數(shù)據(jù)持久化存儲(chǔ)。eg:你有些數(shù)據(jù)想下次運(yùn)行程序的時(shí)候直接使用,或者想把數(shù)據(jù)傳給網(wǎng)絡(luò)上的其他程序,就可以使用pickle打包,那邊的python程序用pickle反序列化就可以了。


1.2 pickle模塊的所有函數(shù)

In [32]: import pickle 

In [33]: dir(pickle)
Out[33]: 
 'classmap',
 'compatible_formats',
 'decode_long',
 'dispatch_table',
 'dump',
 'dumps',
 'encode_long',
 'format_version',
 'load',
 'loads',
 'marshal',
 'mloads',
 're',
 'struct',
 'sys',
 'whichmodule']


1.3 pickle的常用方法

    1.pickle.dump("數(shù)據(jù)",文件名) 把字典轉(zhuǎn)為二進(jìn)制

    2.pickle.load("文件名")    把二進(jìn)制轉(zhuǎn)為字典


##pickle代碼小練習(xí)

In [32]: import pickle 
In [37]: users = {'AA': 'we231', 'Xman': '123', 'tt': '123', 'woniu': '21'}

In [39]: fo = open("test.txt",'wb')

In [42]: fo = open("test.txt",'wb')

In [43]: pickle.dump(users,fo)        #數(shù)據(jù)---> 文件

In [44]: fo.close()

##查看test.txt文件內(nèi)容
[root@test ketang]# cat test.txt 
(dp0
S'AA'
p1
S'we231'
p2
sS'Xman'
p3
S'123'
p4
sS'tt'
p5
g4
sS'woniu'
p6
S'21'
p7
s.[root@test ketang]#

In [9]: fi = open('test.txt','rb+')

In [10]: print pickle.load(fi)
{'AA': 'we231', 'Xman': '123', 'tt': '123', 'woniu': '21'}


1.4 通過(guò)pickle實(shí)現(xiàn)用戶(hù)的增刪改查

#/usr/local/python
#coding:utf-8
'''
    ##使用pickle實(shí)現(xiàn)對(duì)users.txt文件中用戶(hù)密碼的增、刪、改、查功能(具體見(jiàn)github06/pickle代碼)
'''
from  pickle import dump ,load

#定義全局變量filename,用于測(cè)試
filename = 'users.txt'

##注意事先要將users寫(xiě)入到users.txt文件中(此處在1.3中ipython的環(huán)境中操作過(guò)了)
users = {'AA': 'AA123', 'Xman': '123', 'tt': '123', 'woniu': '21', 'KK': 'k123'}

#獲取所有用戶(hù)名密碼,從filename文件中讀取
def getUsers():
    with open(filename,'rb') as readf:
        res = load(readf)
    return res

#添加用戶(hù)
def addUser(name,password):
    tmp = getUsers()
    if  (not name) or (not password):
        errmsg = "Wrong name or password"
        return errmsg
    if (name in tmp):
        errmsg = "name is exists"
        return errmsg
    tmp[name] = password
    msg =  "%s:%s ---->adding" %(name,password)
    with open(filename,'wb') as updatef:
        dump(tmp,updatef)
    return msg
    
##更改用戶(hù)
def updateUser(name,password):
    tmp = getUsers()
    if name not in tmp:
        errmsg = 'The update username is not exist'
        return errmsg
    msg =  "Update  %s:%s ---->%s" %(tmp[name],password,name)
    tmp[name] = password
        with open(filename,'wb') as updatef:
                dump(tmp,updatef)
        return msg


#刪除用戶(hù)
def deleteUser(name):
    tmp = getUsers()
    if name not in tmp:
        errmsg = 'The delete username is not exist'
        return errmsg
    msg =  "Delete  %s ---->%s" %('users.txt',name)
    tmp.pop(name)
        with open(filename,'wb') as updatef:
                dump(tmp,updatef)
        return msg

##查找用戶(hù)名對(duì)應(yīng)的密碼
def findUser(name):
    tmp = getUsers()
    if name not in tmp :
        errmsg = "The username is not exists"
        return errmsg
    return tmp[name]


##主程序入口
if __name__ == "__main__":
    print getUsers()
    print findUser('')
    print findUser('AA')
    print "add user %s" % ('*' * 40)
    print addUser('pc','pc123')
    print addUser('TT','')
    print addUser('','pc123')
    print addUser('AA','pc123')
    print "update user %s" % ('*' * 40)
    print updateUser('AA1','123')
    print updateUser('AA','AA123')
    print "delete user %s" % ('*' * 40)
    print deleteUser('AA1')
    print deleteUser('pc')


二、MySQL存儲(chǔ)數(shù)據(jù)


2.1 安裝mysql以及mysql擴(kuò)展

yum install -y mysql  mysql-server 

##安裝完成后設(shè)置開(kāi)機(jī)啟動(dòng)以及數(shù)據(jù)庫(kù)密碼
[root@test mysqlData]# chkconfig --level 1234 mysqld  on   #設(shè)置開(kāi)機(jī)啟動(dòng)
[root@test mysqlData]# chkconfig --list mysqld    
mysqld         	0:off	1:on	2:on	3:on	4:on	5:on	6:off
[root@test mysqlData]# 

# /etc/init.d/mysqld  start   啟動(dòng)數(shù)據(jù)庫(kù)
#
[root@test mysqlData]# 
[root@test mysqlData]# netstat -ntpl  ##查看數(shù)據(jù)庫(kù)運(yùn)行狀態(tài)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name   
tcp        0      0 127.0.0.1:2208              0.0.0.0:*                   LISTEN      3014/hpiod          
tcp        0      0 127.0.0.1:199               0.0.0.0:*                   LISTEN      3032/snmpd          
tcp        0      0 0.0.0.0:3306                0.0.0.0:*                   LISTEN      3416/mysqld         
tcp        0      0 0.0.0.0:111                 0.0.0.0:*                   LISTEN      2667/portmap        
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      3102/httpd          
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      3052/sshd           
tcp        0      0 127.0.0.1:631               0.0.0.0:*                   LISTEN      3068/cupsd          
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      3472/sendmail: acce 
tcp        0      0 0.0.0.0:766                 0.0.0.0:*                   LISTEN      2704/rpc.statd      
[root@test mysqlData]# 

##設(shè)置數(shù)據(jù)庫(kù)密碼
##mysqladmin -u 用戶(hù)名  -p"密碼" password 新密碼  ===>回車(chē)后輸入舊密碼

剛安裝數(shù)據(jù)庫(kù)的話(huà)第一次設(shè)置密碼命令
## mysqladmin -uroot password "123456"


##mysql擴(kuò)展安裝
1.yum install python-pip
2. pip   install  MySQL-python

##安裝完成后的檢查(在ipython中import MySQLdb as mysql 無(wú)報(bào)錯(cuò)信息則成功)

In [1]: import MySQLdb as mysql

In [2]:


2.2 數(shù)據(jù)庫(kù)的簡(jiǎn)單操作

##創(chuàng)建庫(kù)
mysql> create database reboot;   #創(chuàng)建庫(kù)
Query OK, 1 row affected (0.01 sec)

mysql> show databases;            #列出所有庫(kù)
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| reboot             |
| reboot10           |
| test               |
+--------------------+
6 rows in set (0.00 sec)

mysql> use reboot;        #切換庫(kù),使用reboot庫(kù)
Database changed

#創(chuàng)建表
mysql> create table users(
    ->     id int AUTO_INCREMENT primary key 
    ->     ,name varchar(20) not null comment '用戶(hù)名' 
    ->     ,name_cn varchar(50) not null comment '中文名' 
    ->     ,password varchar(50) not null comment '用戶(hù)密碼' 
    ->     ,email varchar(50) comment '電子郵件' 
    ->     ,mobile varchar(11) not null comment '手機(jī)號(hào)碼' 
    ->     ,role varchar(10) not null comment '1:sa;2:php;3:ios;4:test'
    ->     ,status tinyint
    ->     ,create_time datetime comment '創(chuàng)建時(shí)間' 
    ->     ,last_time datetime comment '最后登錄時(shí)間' 
    ->     ,unique key  name (name) ) engine=innodb comment '用戶(hù)表';
Query OK, 0 rows affected (0.06 sec)

mysql> desc users;        #查看表信息,表中字段定義及類(lèi)型
+-------------+-------------+------+-----+---------+----------------+
| Field       | Type        | Null | Key | Default | Extra          |
+-------------+-------------+------+-----+---------+----------------+
| id          | int(11)     | NO   | PRI | NULL    | auto_increment |
| name        | varchar(20) | NO   | UNI | NULL    |                |
| name_cn     | varchar(50) | NO   |     | NULL    |                |
| password    | varchar(50) | NO   |     | NULL    |                |
| email       | varchar(50) | YES  |     | NULL    |                |
| mobile      | varchar(11) | NO   |     | NULL    |                |
| role        | varchar(10) | NO   |     | NULL    |                |
| status      | tinyint(4)  | YES  |     | NULL    |                |
| create_time | datetime    | YES  |     | NULL    |                |
| last_time   | datetime    | YES  |     | NULL    |                |
+-------------+-------------+------+-----+---------+----------------+
10 rows in set (0.00 sec)

mysql> show tables;        #查看庫(kù)中有哪些表
+------------------+
| Tables_in_reboot |
+------------------+
| users            |
+------------------+
1 row in set (0.00 sec)

mysql>
##mysql數(shù)據(jù)庫(kù)中插入數(shù)據(jù)
mysql> insert into users (name,name_cn,password,email,mobile,role,status,create_time) values ('ss','ss','ss123 ','ss@chinacache.com','ssss','user','0','2016-11-30  15:37:48');
Query OK, 1 row affected (0.02 sec)


mysql> 
mysql> select * from users;    #查找表中所有數(shù)據(jù)
+----+------+---------+----------+-------------------+--------+------+--------+---------------------+-----------+
| id | name | name_cn | password | email             | mobile | role | status | create_time         | last_time |
+----+------+---------+----------+-------------------+--------+------+--------+---------------------+-----------+
|  1 | ss   | ss      | ss123    | ss@chinacache.com | ssss   | user |      0 | 2016-11-30 15:37:48 | NULL      |
+----+------+---------+----------+-------------------+--------+------+--------+---------------------+-----------+
1 row in set (0.00 sec)


2.3 python交互環(huán)境下對(duì)mysql的操作

##導(dǎo)入數(shù)據(jù)庫(kù)
In [8]: import MySQLdb as mysql
##連接數(shù)據(jù)庫(kù)
In [9]: data = mysql.connect(user='root',passwd='123456',db='reboot',charset='utf8')

##建立游標(biāo),添加這行后數(shù)據(jù)庫(kù)就初始化完成
In [10]: cur = data.cursor()

In [11]: data.autocommit(True)  ##設(shè)置自動(dòng)提交,比較重要

##在ipython端添加數(shù)據(jù)

#在ipython段查詢(xún)所有數(shù)據(jù)
In [13]: cur.execute('select * from users')
Out[13]: 1L

In [14]: import datetime    #導(dǎo)入datetime

In [15]: ##datetime模塊可以實(shí)現(xiàn)在數(shù)據(jù)庫(kù)中create_time生成時(shí)間

In [16]: sql = "insert into users(name,name_cn,password,email,mobile,role,status,create_time) values ('cc'
    ...: ,'cc','cC23 ','CC@chinacache.com','CCC','user','0','%s') " %(datetime.datetime.now().strftime("%Y
    ...: -%m-%d  %H:%M:%S"))

In [17]: print sql
insert into users(name,name_cn,password,email,mobile,role,status,create_time) values ('cc','cc','cC23 ','CC@chinacache.com','CCC','user','0','2016-11-30  16:04:33') 

In [18]: cur.execute(sql)
Out[18]: 1L
#再次查詢(xún)所有數(shù)據(jù)發(fā)現(xiàn)新增加了一條數(shù)據(jù)
In [19]: cur.execute("select * from users;")
Out[19]: 2L

##在mysql段查詢(xún)所有數(shù)據(jù)確認(rèn)新增數(shù)據(jù)
mysql> select * from users;
+----+------+---------+----------+-------------------+--------+------+--------+---------------------+-----------+
| id | name | name_cn | password | email             | mobile | role | status | create_time         | last_time |
+----+------+---------+----------+-------------------+--------+------+--------+---------------------+-----------+
|  1 | ss   | ss      | ss123    | ss@chinacache.com | ssss   | user |      0 | 2016-11-30 15:37:48 | NULL      |
|  2 | cc   | cc      | cC23     | CC@chinacache.com | CCC    | user |      0 | 2016-11-30 16:04:33 | NULL      |
+----+------+---------+----------+-------------------+--------+------+--------+---------------------+-----------+
2 rows in set (0.00 sec)

mysql> 

##ipython交互下查找數(shù)據(jù)


###查詢(xún)所有數(shù)據(jù)
In [20]: select_sql = "select name,name_cn,password,email,mobile,role,status,create_time from users"

In [21]: cur.execute(select_sql)
Out[21]: 2L

In [22]: res = cur.fetchall()      ##查找所有數(shù)據(jù)使用cur.fetchall(),單條數(shù)據(jù)則使用cur.fetchone()

In [23]: print res
((u'ss', u'ss', u'ss123 ', u'ss@chinacache.com', u'ssss', u'user', 0, datetime.datetime(2016, 11, 30, 15, 37, 48)), (u'cc', u'cc', u'cC23 ', u'CC@chinacache.com', u'CCC', u'user', 0, datetime.datetime(2016, 11, 30, 16, 4, 33)))


###查詢(xún)單條數(shù)據(jù)
In [24]: select_sql = "select name,name_cn,password,email,mobile,role,status,create_time from users where 
    ...: name = 'ss'"

In [25]: cur.execute(select_sql)
Out[25]: 1L

In [26]: res = cur.fetchone()

In [27]: print res
(u'ss', u'ss', u'ss123 ', u'ss@chinacache.com', u'ssss', u'user', 0, datetime.datetime(2016, 11, 30, 15, 37, 48))

In [28]: 

###ipython交互模式下查詢(xún)所有數(shù)據(jù)以及將數(shù)據(jù)重組成我們想要的形式
In [36]: select_sql = "select name,name_cn,password,email,mobile,role,status,create_time from users "

In [37]: cur.execute(select_sql)
Out[37]: 4L

In [38]: res = cur.fetchall()

In [39]: print res
((u'ss', u'ss', u'ss123 ', u'ss@chinacache.com', u'ssss', u'user', 0, datetime.datetime(2016, 11, 30, 15, 37, 48)), (u'cc', u'cc', u'cC23 ', u'CC@chinacache.com', u'CCC', u'user', 0, datetime.datetime(2016, 11, 30, 16, 4, 33)), (u'admin', u'admin', u'admin ', u'admin@cc.com', u'admin', u'admin', 0, datetime.datetime(2016, 11, 30, 16, 25, 17)), (u'TT', u'TT', u'tt123 ', u'tt@cc.com', u'123223', u'sa', 0, datetime.datetime(2016, 11, 30, 16, 26, 17)))

##思考:如何將上述res更改成為我們想要的字典形式
In [40]: fields = ['name','name_cn','password','email','mobile','role','status','create_time']

原生實(shí)現(xiàn)方式:
In [7]: select_sql = "select %s from users" %','.join(fields)

In [8]: print select_sql
select name,name_cn,password,email,mobile,role,status,create_time from users

In [9]: cur.execute(select_sql)
Out[9]: 4L

In [10]: res = cur.fetchall()

In [11]: res
Out[11]: 
((u'ss',
  u'ss',
  u'ss123 ',
  u'ss@chinacache.com',
  u'ssss',
  u'user',
  0,
  datetime.datetime(2016, 11, 30, 15, 37, 48)),
 (u'cc',
  u'cc',
  u'cC23 ',
  u'CC@chinacache.com',
  u'CCC',
  u'user',
  0,
  datetime.datetime(2016, 11, 30, 16, 4, 33)),
 (u'admin',
  u'admin',
  u'admin ',
  u'admin@cc.com',
  u'admin',
  u'admin',
  0,
  datetime.datetime(2016, 11, 30, 16, 25, 17)),
 (u'TT',
  u'TT',
  u'tt123 ',
  u'tt@cc.com',
  u'123223',
  u'sa',
  0,
  datetime.datetime(2016, 11, 30, 16, 26, 17)))

In [12]: users = [] 

In [13]: for row in res :
    ...:     user = {}
    ...:     for k ,v in enumerate(fields):
    ...:         user[v] = row[k]
    ...:     users.append(user)
    ...:     

In [14]: users
Out[14]: 
[{'create_time': datetime.datetime(2016, 11, 30, 15, 37, 48),
  'email': u'ss@chinacache.com',
  'mobile': u'ssss',
  'name': u'ss',
  'name_cn': u'ss',
  'password': u'ss123 ',
  'role': u'user',
  'status': 0},
 {'create_time': datetime.datetime(2016, 11, 30, 16, 4, 33),
  'email': u'CC@chinacache.com',
  'mobile': u'CCC',
  'name': u'cc',
  'name_cn': u'cc',
  'password': u'cC23 ',
  'role': u'user',
  'status': 0},
 {'create_time': datetime.datetime(2016, 11, 30, 16, 25, 17),
  'email': u'admin@cc.com',
  'mobile': u'admin',
  'name': u'admin',
  'name_cn': u'admin',
  'password': u'admin ',
  'role': u'admin',
  'status': 0},
 {'create_time': datetime.datetime(2016, 11, 30, 16, 26, 17),
  'email': u'tt@cc.com',
  'mobile': u'123223',
  'name': u'TT',
  'name_cn': u'TT',
  'password': u'tt123 ',
  'role': u'sa',
  'status': 0}]

In [15]: 

###高階的進(jìn)階方式代碼(字典生成式 + 列表生成式 一行搞定)
In [45]: users = [dict((v,row[k]) for k ,v in enumerate(fields)) for row in res ]

###關(guān)閉游標(biāo)和數(shù)據(jù)庫(kù)
In [15]: cur.close()

In [16]: data.close()


2.4 自己感悟的數(shù)據(jù)庫(kù)操作


  2.4.1 高階用法記錄 【字典生成式 + 列表生成式 簡(jiǎn)化代碼】

如下面代碼可用 users = [ dict((v,row[k]) for k ,v in enumerate(fields)) for row in res ]

In [12]: users = []
In [13]: for row in res :
    ...:     user = {}
    ...:     for k ,v in enumerate(fields):
    ...:         user[v] = row[k]
    ...:     users.append(user)
    ...:


  2.4.2  python搭建一個(gè)臨時(shí)的下載服務(wù)器;

    python -m SimpleHTTPServer(默認(rèn)會(huì)解析當(dāng)前目錄下的html文件)

從零開(kāi)始學(xué)Python-day7

三、總結(jié)

    python數(shù)據(jù)庫(kù)操作流程


    1.導(dǎo)入mysql擴(kuò)展模塊, import MySQLdb  as  mysql


    2.鏈接數(shù)據(jù)庫(kù)       db = mysql.connect(各種參數(shù))

    

    3.建立游標(biāo),   cur = db.cursor() ,自此數(shù)據(jù)庫(kù)初始化完成,可以干活了


    4.編寫(xiě)mysql的語(yǔ)句(增刪改查)   sql = "*****"


    5.執(zhí)行sql語(yǔ)句  cur.execute(sql)  db.commit() ===>數(shù)據(jù)提交


    6.查詢(xún)   分為兩種 (在mysql中查詢(xún)  select * from users)


        1.查詢(xún)單條記錄, cur.fetchone()

        2.查詢(xún)多條記錄  cur.fetchall()


    7.注意此時(shí),在mysql中查看數(shù)據(jù)還是未更新的,需要關(guān)閉游標(biāo)

        db.commit() ===>數(shù)據(jù)提交

        將內(nèi)存中的數(shù)據(jù)存儲(chǔ)到數(shù)據(jù)庫(kù)的表上。

        mysql設(shè)置為默認(rèn)自動(dòng)提交  show variables like 'autocommit%';

        或者添加db.autocommit(True) 設(shè)置交互端自動(dòng)提交數(shù)據(jù)


    8.關(guān)閉游標(biāo)和數(shù)據(jù)庫(kù)

        cur.close()

        conn.close()


向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI