第5课:Python操作Mysql

开发项目,免不了和数据库打交道,这里以mysql为例,来说明python怎么进行增删改查操作

假设我们有个godeye表  字段  id  name  status
第一步我们需要python操作mysql用到的MySQLdb包,下载安装即可

#查询数据
import MySQLdb
 
try:
    conn=MySQLdb.connect(host='localhost',user='root',passwd='',db='test',port=3306)
    cur=conn.cursor()
    cur.execute('select * from godeye')
    rows = cur.fetchall()#查询一条数据用cur.fetchone() 返回值是个元祖
    for row in rows:
        print row
    cur.close()
    conn.close()
except MySQLdb.Error,e:
     print "Mysql Error %d: %s" % (e.args[0], e.args[1])
     

#写数据
import MySQLdb
import time
import sys

#reload(sys)
#sys.setdefaultencoding('utf-8')
 
try:
    conn = MySQLdb.connect(host='localhost', user='root', passwd='', db='test', port=3306, charset='utf8')
    cur  = conn.cursor()
     
    time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime() )
    #sys.exit()
    value = ['godeye', 0, time]
    
    cur.execute('insert into godeye (name, status, time) values (%s,%s,%s)', value)
    
    cur.execute('update godeye set name="I am godeye" where id = 1')
 
    conn.commit()
    cur.close()
    conn.close()
 
except MySQLdb.Error, e:
     print "Mysql Error %d: %s" % (e.args[0], e.args[1])