实现Python连接Mysqln以及应用
python 连接mysql数据库,是python应用的一个非常重要的模块,Pytho连接Mysqln需要连接导入python的mysql模块,通过python连接数据库,我们可以实现对本地的资源状态实现实时监控。
1、首先我们需要先安装MySQL模块
1 | [root@centos mem]# yum install MySQL-python -y |
2、接下来我们就可以直接脚本了
1 2 3 4 5 6 7 8 9 | [root@centos pytonjiaoben]# cat mysql.py import MySQLdb as mysql ###这是导入 MySQL-python模块con = mysql.connect(user="root", passwd="123456", \ db="mem", host="127.0.0.1") ###连接本地的数据库mem,指定数据库的名称,主机地址,用户名和密码con.autocommit(True) ###设置为自动提交模式,表示把每一个查询操作,作为1个独立的事务处理,马上执行cur = con.cursor() ###创建1个游标对象for i in range(10): ###这里做个for循环写入数据 sql = 'insert into mem values(%d, "user%d")'%(i,i) ###定义sql语句 cur.execute(sql) ##执行sql语句 |
注意:
##数据库和数据表必须是你先创建的,而且mysql一定要设置密码才行。
3、执行结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | mysql> select * from mem;+------+---------+| id | name |+------+---------+| 0 | user0 || 1 | user1 || 2 | user2 || 3 | user3 || 4 | user4 || 5 | user5 || 6 | user6 || 7 | user7 || 8 | user8 || 9 | user9 | |
当我们执行脚本后,我们发现数据已经写得数据库里面了
4、现在我们可能会有疑问,这样写进去又有什么用,那好,我们接着写个脚本,关于mysql的应用的。现在我们对服务器的内存使用情况,写入到mysql上,写得mysql上就可以通过flask调用,实现对本地资源实现监控。
我们查看一下我们内存文件
1 2 3 4 5 6 | [root@centos pytonjiaoben]# cat /proc/meminfo MemTotal: 1528700 kBMemFree: 224072 kBBuffers: 130432 kBCached: 604432 kBSwapCached: 8440 kB |
6、编写脚本,获取内存的使用量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | [root@centos pytonjiaoben]# cat mem/mysql.py # -*- coding:utf-8 -*-import timeimport osimport MySQLdb as mysqldb = mysql.connect(user="root", passwd="123456", db="memory", host="localhost")db.autocommit(True)cur=db.cursor()def saveMem(): ##获取memory的total、free、buff的量 a="awk 'NR==1{print $2}' /proc/meminfo" file = os.popen(a) total=int(file.read()) b="awk 'NR==2{print $2}' /proc/meminfo" file =os.popen(b) free =int(file.read()) c="awk 'NR==3{print $2}' /proc/meminfo" file = os.popen(c) buffer =int(file.read()) d="awk 'NR==4{print $2}' /proc/meminfo" file =os.popen(d) cache =int(file.read()) mem_used=total-free-buffer-cache print mem_used/1024 #mem = mem_used/1024 cur_time = int(time.time()) sql = 'insert into memory (memory, time) value (%s,%s)'%(mem_used,cur_time) cur.execute(sql)while True:saveMem()time.sleep(1) # sleep 1 second |
7、查看结果
1 2 3 4 5 | [root@centos pytonjiaoben]# python mem/mysql.py 562563563563 |
###查看数据库
1 2 3 4 5 6 7 8 | mysql> select * from memory;+--------+------------+| memory | time |+--------+------------+| 577012 | 1511869204 || 577004 | 1511869205 || 576872 | 1511869206 |+--------+------------+ |
8、我们会发现它会实时获取内存的使用情况,这样我们的目的也达到了,只要有数据输入到mysql中,接下来只要通过flask调用,做成图,就可以实现监控了。