12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
ADADADADAD
mysql数据库 时间:2024-12-25 09:56:40
作者:文/会员上传
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
实现Python连接Mysqln以及应用 python 连接mysql数据库,是python应用的一个非常重要的模块,Pytho连接Mysqln需要连接导入python的mysql模块,通过python连接数据库,我们可以实现
以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。
实现Python连接Mysqln以及应用
python 连接mysql数据库,是python应用的一个非常重要的模块,Pytho连接Mysqln需要连接导入python的mysql模块,通过python连接数据库,我们可以实现对本地的资源状态实现实时监控。
1、首先我们需要先安装MySQL模块
[root@centosmem]#yuminstallMySQL-python-y
2、接下来我们就可以直接脚本了
[root@centospytonjiaoben]#catmysql.pyimportMySQLdbasmysql###这是导入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个游标对象foriinrange(10):###这里做个for循环写入数据sql='insertintomemvalues(%d,"user%d")'%(i,i)###定义sql语句cur.execute(sql)##执行sql语句
注意:
##数据库和数据表必须是你先创建的,而且mysql一定要设置密码才行。
3、执行结果
mysql>select*frommem;+------+---------+|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调用,实现对本地资源实现监控。
我们查看一下我们内存文件
[root@centospytonjiaoben]#cat/proc/meminfoMemTotal:1528700kBMemFree:224072kBBuffers:130432kBCached:604432kBSwapCached:8440kB
6、编写脚本,获取内存的使用量
[root@centospytonjiaoben]#catmem/mysql.py#-*-coding:utf-8-*-importtimeimportosimportMySQLdbasmysqldb=mysql.connect(user="root",passwd="123456",db="memory",host="localhost")db.autocommit(True)cur=db.cursor()defsaveMem():##获取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-cacheprintmem_used/1024#mem=mem_used/1024cur_time=int(time.time())sql='insertintomemory(memory,time)value(%s,%s)'%(mem_used,cur_time)cur.execute(sql)whileTrue:saveMem()time.sleep(1)#sleep1second
7、查看结果
[root@centospytonjiaoben]#pythonmem/mysql.py562563563563
###查看数据库
mysql>select*frommemory;+--------+------------+|memory|time|+--------+------------+|577012|1511869204||577004|1511869205||576872|1511869206|+--------+------------+
8、我们会发现它会实时获取内存的使用情况,这样我们的目的也达到了,只要有数据输入到mysql中,接下来只要通过flask调用,做成图,就可以实现监控了。
11-20
11-19
11-20
11-20
11-20
11-19
11-20
11-20
11-19
11-20
11-19
11-19
11-19
11-19
11-19
11-19