- #!/usr/bin/env python
- #coding:utf-8
- """
- 这个程序只是简单测试MySQLdb对mysql数据库的增删改查,中文的插入,再表的默认编码是utf8或者gbk的情况下
- 都可以正常插入,不管数据库的默认编码,当表的默认编码是latin1时,插入中文失败
- 对数据库进行修改以后需要调用commit方法来进行提交,才能再数据库中看到修改的情况
- """
- imp
ort MySQLdb - conn=MySQLdb.connect(host="127.0.0.1",user="root",passwd="1q2w3e4r",db="mysite2",charset="utf8")
- c=conn.cursor()
- #首次进行查询如果有中文应该可以正常显示
- sql="select name,id from zhanbu order by id desc limit 1 "
- #c.execute("set names utf8")
- #c.execute("set character_set_client=utf8")
- #c.execute("set character_set_results=utf8")
- d=c.execute(sql)
- dd=c.fetchall()
- #print d
- iid=1
- if len(dd)>0:
- iid=dd[0][1]
- print "第一次查询"
- for i in dd:
- print i,i[0]
- charset = conn.character_set_name()
- #query = query.encode(charset)
- print charset
- #print query
- #增加
- #进行中文插入
- print "插入成功后"
- content="中文"
- sql="insert into zhanbu(id,name) values(%d,'%s')"%(iid+1, content)
- #print sql
- d=c.execute(sql)
- conn.commit()
- #中文插入以后进行查询,看是否能够正常显示
- sql="select name,id from zhanbu order by id desc limit 1 "
- d=c.execute(sql)
- dd=c.fetchall()
- for i in dd:
- print i[0]
- #插入完成后进行修改
- print "修改成功后"
- appendcontent="追加"
- sql="update zhanbu set name='%s' where id=%d"%(appendcontent,iid+1)
- d=c.execute(sql)
- conn.commit()
- sql="select name,id from zhanbu order by id desc limit 1 "
- d=c.execute(sql)
- dd=c.fetchall()
- for i in dd:
- print i[0]
- #修改完成以后删除数据
- print "删除数据以后"
- sql="delete from zhanbu where id=%d"%(iid+1,)
- d=c.execute(sql)
- conn.commit()
- sql="select name,id from zhanbu order by id desc limit 1 "
- d=c.execute(sql)
- dd=c.fetchall()
- for i in dd:
- print i[0]
- c.close()
- conn.close()