首页 > 代码库 > python学习道路(day12note)(mysql操作,python链接mysql,redis)

python学习道路(day12note)(mysql操作,python链接mysql,redis)

1,针对mysql操作

  1 SET PASSWORD FOR root@localhost = PASSWORD(newpass); 设置密码
  2 update user set password=passworD("test") where user=root;修改密码
  3 flush privileges;
  4 grant all on *.* to root@% identified by your_password;  
  5 mysql> select user,password,host from mysql.user;
  6 +------+-------------------------------------------+-----------+
  7 | user | password                                  | host      |
  8 +------+-------------------------------------------+-----------+
  9 | root | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 | localhost |
 10 | root |                                           | 127.0.0.1 |
 11 | root |                                           | ::1       |
 12 |      |                                           | localhost |
 13 | repl | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 | 10.0.5.44 |
 14 | root | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 | 10.0.5.44 |
 15 +------+-------------------------------------------+-----------+
 16 当设定密码后,如果要想更改密码如何操作呢?
 17 mysqladmin -u root -p password "123456789"
 18 Enter password:
 19 输入原来root的密码就可以更改密码了。
 20 【连接数据库】
 21 刚刚讲过通过使用mysql -u root -p 就可以连接数据库了,但这只是连接的本地的数据库’localhost’,然后有很多时候都是去连接网络中的某一个主机上的mysql。
 22 mysql -u user1 -p –P 3306 -h 10.0.2.69
 23 其中-P(大写)指定远程主机mysql的绑定端口,默认都是3306;-h指定远程主机的IP
 24 
 25 3. 查看某个表的字段
 26 mysql> desc func; //func 是表名
 27 +-------+------------------------------+------+-----+---------+-------+
 28 | Field | Type | Null | Key | Default | Extra |
 29 +-------+------------------------------+------+-----+---------+-------+
 30 | name | char(64) | NO | PRI | | |
 31 | ret | tinyint(1) | NO | | 0 | |
 32 | dl | char(128) | NO | | | |
 33 | type | enum(function,aggregate) | NO | | NULL | |
 34 +-------+------------------------------+------+-----+---------+-------+
 35 4. 查看某个表的表结构(创建表时的详细结构)
 36 mysql> show create table func;
 37 |Table | CreateTable |
 38 | func | CREATE TABLE `func` (
 39 `name` char(64) collate utf8_bin NOT NULL default ‘‘,
 40 `ret` tinyint(1) NOT NULL default 0,
 41 `dl` char(128) collate utf8_bin NOT NULL default ‘‘,
 42 `type` enum(function,aggregate) character set utf8 NOT NULL,
 43 PRIMARY KEY (`name`)
 44 ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT=User defined functions |
 45 +-------+----------------------------------------------------------------------------------------------------------------------
 46 
 47 5. 查看当前是哪个用户
 48 mysql> select user();
 49 +----------------+
 50 | user() |
 51 +----------------+
 52 | root@localhost |
 53 +----------------+
 54 6. 查看当前所在数据库
 55 mysql> select database();
 56 +------------+
 57 | database() |
 58 +------------+
 59 | mysql |
 60 +------------+
 61 7. 创建一个新库
 62 mysql> create database db1;
 63 Query OK, 1 row affected (0.04 sec)
 64 8. 创建一个表
 65 mysql> create table t1 ( `id` int(4), `name` char(40));
 66 Query OK, 0 rows affected (0.02 sec)
 67 mysql> desc t1;
 68 +-------+----------+------+-----+---------+-------+
 69 | Field | Type | Null | Key | Default | Extra |
 70 +-------+----------+------+-----+---------+-------+
 71 | id | int(4) | YES | | NULL | |
 72 | name | char(40) | YES | | NULL | |
 73 +-------+----------+------+-----+---------+-------+
 74 9. 查看当前数据库版本
 75 mysql> select version();
 76 +-----------+
 77 | version() |
 78 +-----------+
 79 | 5.0.86 |
 80 +-----------+
 81 10. 查看当前系统时间
 82 mysql> select current_date, current_time;
 83 +--------------+--------------+
 84 | current_date | current_time |
 85 +--------------+--------------+
 86 | 2011-05-31 | 08:52:50 |
 87 +--------------+--------------+
 88 11. 查看当前mysql的状态
 89 mysql> show status;
 90 +-----------------------------------+----------+
 91 | Variable_name | Value |
 92 +-----------------------------------+----------+
 93 | Aborted_clients | 0 |
 94 | Aborted_connects | 1 |
 95 | Binlog_cache_disk_use | 0 |
 96 | Binlog_cache_use | 0 |
 97 | Bytes_received | 664 |
 98 | Bytes_sent | 6703 |
 99 这个命令打出很多东西,显示你的mysql状态。
100 12. 查看mysql的参数
101 mysql> show variables;
102 很多参数都是可以在/etc/my.cnf中定义的。
103 13. 创建一个普通用户并授权
104 mysql> grant all on *.* to user1 identified by 123456;
105 Query OK, 0 rows affected (0.01 sec)
106 all 表示所有的权限(读、写、查询、删除等等操作),*.*前面的*表示所有的数据库,后面的*表示所有的表,identified by 后面跟密码,用单引号括起来。这里的user1指的是localhost上的user1,如果是给网络上的其他机器上的某个用户授权则这样:
107 mysql> grant all on db1.* to user2@10.0.2.100 identified by 123456;
108 Query OK, 0 rows affected (0.00 sec)
109 用户和主机的IP之间有一个@,另外主机IP那里可以用%替代,表示所有主机。例如:
110 mysql> grant all on db1.* to user3@% identified by 123456;
111 Query OK, 0 rows affected (0.00 sec)
112 【一些常用的sql】
113 1. 查询语句
114 mysql> select count(*) from mysql.user;
115 mysql.user表示mysql库的user表;count(*)表示表中共有多少行。
116 mysql> select * from mysql.db;
117 查询mysql库的db表中的所有数据
118 mysql> select db from mysql.db;
119 查询mysql库db表的db段。
120 mysql> select * from mysql.db where host like 10.0.%;
121 查询mysql库db表host字段like 10.0.% 的行,这里的%表示匹配所有,类似于前面介绍的通配符。
122 2. 插入一行
123 mysql> insert into db1.t1 values (1, abc);
124 Query OK, 1 row affected (0.00 sec)
125 t1表在前面已经创建过。
126 mysql> select * from db1.t1;
127 +------+------+
128 | id | name |
129 +------+------+
130 | 1 | abc |
131 +------+------+
132 3. 更改某一行
133 mysql> update db1.t1 set name=aaa where id=1;
134 Query OK, 1 row affected (0.02 sec)
135 Rows matched: 1 Changed: 1 Warnings: 0
136 这样就把原来id为1的那行中的name改成’aaa’
137 4. 删除表
138 mysql> drop table db1.t1;
139 Query OK, 0 rows affected (0.01 sec)
140 5. 删除数据库
141 mysql> drop database db1;
142 Query OK, 0 rows affected (0.07 sec)
143 6. 备份与恢复库
144 mysqldump -uroot -p mysql >mysql.sql
145 这里的mysqldump 就是备份的工具了,-p后面的mysql指的是mysql库,把备份的文件重定向到mysql.sql。如果恢复的话,只要:
146 mysql -uroot -p mysql < mysql.sql

 

2.python链接数据库并执行备份

 1 import pymysql
 2 import os, sys, tarfile, datetime, re, time, subprocess
 3 
 4 Date = time.strftime(%Y%m%d_%H-%M)
 5 print(Date)
 6 
 7 flage = None
 8 Flage = None
 9 
10 class mysql_backup(object):
11     def __init__(self,res,host,user,pwd,gamedb,path):
12         self.res = res
13         self.host = host
14         self.user = user
15         self.pwd = pwd
16         self.gamedb = gamedb
17         self.path = path
18 
19     def connect(self):
20         f = open(self.path + "errlog_db.log","a+",encoding="utf-8")
21         try:
22             conn = pymysql.connect(host=self.host, user=self.user, passwd=self.pwd, db=self.gamedb)
23             print("connect ok")
24             global flage
25             flage = True
26         except Exception as e:
27             f.write(Date + : + connect to mysqldb error!!! + \n)
28             sys.exit()
29         conn.close()
30         f.close()
31 
32     def sqlfile(self):
33         global flage, Flage
34         if flage:
35             f = open(self.path + "errlog_db.log", "a+", encoding="utf-8")
36             try:
37                 os.system(%s -u%s -p%s -h%s %s >> %sgamedb.sql % (self.res,self.user,self.pwd,self.host,self.gamedb,self.path))
38                 tarsql = tarfile.open( self.path + Date + .tar, w)
39                 tarsql.add(self.path + gamedb.sql,arcname= Date + ".gamedb.sql")
40                 tarsql.close()
41                 Flage = True
42                 print("sqlfile ok %s" % self.user)
43             except Exception as e:
44                 f.write(Date + : + sqlfile to tar error!!! + \n)
45                 sys.exit()
46             f.close()
47 
48     def refile(self):
49         global flage, Flage
50         if flage and Flage:
51             if os.path.isfile(self.path + gamedb.sql):
52                 os.system("rm -f" + " " + self.path + "gamedb.sql")
53                 print("refiel ok")
54 
55     def errlog(self):
56         if os.path.isdir(self.path) is False:
57             os.makedirs(self.path)
58             print("path ok")
59         if os.path.isfile(self.path + errlog_db.log) is False:
60             os.system("touch" + " " + self.path + "errlog_db.log")
61             print("errlog ok")
62 
63     def oldfile(self):
64         settime= (datetime.datetime.now() - datetime.timedelta(days=1)).strftime(%Y%m%d) #获取到30天前的时间
65         settime = int(settime)
66 
67         for dirpath,dirnames,filenames in os.walk(self.path):
68             for file in filenames:
69                 if file != errlog_db.log:
70                     filetime = time.strftime(%Y%m%d, time.localtime(os.stat(self.path + file).st_ctime))  #获取文件时间
71                     filetime = int(filetime)
72                     print(file)
73                     if settime == filetime:
74                         os.remove(self.path + file)
75 
76 #需要你手动更改打开的文件位置,注意#行需要更改
77 def config():
78     file = open("start", "r", encoding="utf-8")    #打开文件位置
79     host = re.findall(r-db_host="(\w.*?)", file.read())
80     str_host = ‘‘.join(host)
81     file.close()
82 
83     file = open("start","r",encoding="utf-8")
84     dbname = re.findall(r-db_name="(\w.*?)",file.read())   #打开文件位置
85     str_dbname = ‘‘.join(dbname)
86     file.close()
87 
88     res = subprocess.Popen("which mysqldump", shell=True, stdout=subprocess.PIPE)
89     res = res.stdout.read().decode().strip()
90 
91     parameter = mysql_backup(res,str_host,root,123456,str_dbname,r/data/backup_db/)   #用户,密码需要更改,路径
92     parameter.errlog()
93     parameter.connect()
94     parameter.sqlfile()
95     parameter.refile()
96     parameter.oldfile()
97 
98 if __name__ == "__main__":
99     config()

 

3.redis操作。。。。

python学习道路(day12note)(mysql操作,python链接mysql,redis)