Centos下Python连接mysql的小例子

 

 

 

 

 

python  mysql 以及mysql-python的插件

yum install python
yum install MySQL-server
yum install MySQL-python

 

例子说明:从日志文件中筛选出有效值,插入到Mysql数据库中

#!/usr/bin/python
import MySQLdb
import os
import sys
fileHandle = open ( '/var/log/13-11-05.log' )
try:
 conn=MySQLdb.connect(host='ipAddress',user='developer',passwd='developer',db='test',port=3306)
 mycursor = conn.cursor()
 for  line in  fileHandle.readlines():
  startIPPos = line.index('(')
  endIPPos = line.index(')')
  ipAddr = line[startIPPos+1:endIPPos]
  startUPos = line.index('#####')
  endUPos = line.index('pts')
  uName = line[startUPos+5:endUPos]
  mycursor.execute('insert into MyRecord (name,ip,record) values(%s,%s,%s)',(ipAddr,uName,line))
  conn.commit()
except MySQLdb.Error,e:
 print "Mysql Error %d: %s" % (e.args[0], e.args[1])
mycursor.close()
conn.close()
fileHandle.close()

 

你可能感兴趣的:(Python+Mysql)