实现Python连接Mysqln以及应用

  

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,实现Python连接Mysqln以及应用

,,python连接mysql数据库,是python应用的一个非常重要的模块,Pytho连接Mysqln需要连接pythonmysql

<强> mysql

(root@centos  mem) #, yum , install , MySQL-python ,, - y

<强> 2,接下来我们就可以直接脚本了

[root@centos  pytonjiaoben] #, cat  mysql.py    import  MySQLdb , as , mysql ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, # # #这是导入,MySQL-python模块   con =, mysql.connect(用户=皉oot",, passwd=?23456“,, \   ,,,,,,,,,,,,,,,,,,,db=癿em",,主机=?27.0.0.1"),,,,,,,,, # # #连接本地的数据库mem,指定数据库的名称,主机地址,用户名和密码   con.autocommit(真正的),,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,# # #设置为自动提交模式,表示把每一个查询操作,作为1个独立的事务处理,马上执行   时间=cur  con.cursor(),,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, # # #创建1个游标对象   for 小姐:拷贝范围(10):,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,# # #这里做个为循环写入数据   ,,sql =, & # 39; insert  into  mem 值(% d,“用户% d") & # 39; %(我),,,# # #定义sql语句   ,才能cur.execute (sql),,,, # #执行sql语句

<强>

<强> 3,执行结果

mysql>, select  *,得到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上就可以通过

[root@centos  pytonjiaoben] #, cat /proc/meminfo    MemTotal:,,,,,,,, 1528700 kB   内存清理:,,,,,,,,,,224072 kB   缓冲区:,,,,,,,,,,130432 kB   缓存:,,,,,,,,,,,604432 kB   SwapCached:,,,,,,,,,, 8440 kB


<强> 6,编写脚本,获取内存的使用量

[root@centos  pytonjiaoben] #, cat  mem/mysql.py    #,- *安康;编码:utf-8  - *   import 时间   import 操作系统   import  MySQLdb  as  mysql   db =, mysql.connect(用户=皉oot",, passwd=?23456“,, db=癿emory",,主机=發ocalhost")   db.autocommit(真正的)   坏蛋=db.cursor ()   def  saveMem():,,,,,,,,,,,, # #获取内存的,免费的,浅黄色的量   ,,,,a=癮wk  & # 39; NR==1 {print  $ 2} & # 39;,/proc/meminfo"   ,,,,file =, os.popen (a)   ,,,,总=int(以())   ,,,,b=癮wk  & # 39; NR==2 {print  $ 2} & # 39;,/proc/meminfo",,,,,   ,,,,file =os.popen (b)   ,,,,free =int(以())   ,,,,c=癮wk  & # 39; NR==3 {print  $ 2} & # 39;,/proc/meminfo"   ,,,,file =, os.popen (c)   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

实现Python连接Mysqln以及应用