python连接MYSql数据库python连接MYSql数据库 使用 MySQLdb

来源:互联网 发布:淘宝大学女装推荐 知乎 编辑:程序博客网 时间:2024/05/16 14:04

安装:下载 MySQL-python-1.2.2.tar.gz

            $ tar xfz MySQL-python-1.2.1.tar.gz
$ cd MySQL-python-1.2.1
$ python setup.py build
完成

编写python脚本需要注意:python脚本保存的编码格式需要和数据库连接中的charset相符,
否则将出现乱码
#coding=gb2312
import MySQLdb as mydb
db = mydb.connect(host='192.168.0.*',user='***',passwd='***',db='test', charset="gb2312")

cur = db.cursor()
sql = unicode("select cgs_svcid from t_test_dscgs_svc where cpqs = '闽A'","gb2312")
print sql
cur.execute(sql)
while 1:
a = cur.fetchone()
if a:
for x in a:
print x,
else:break
cur.close()

cur = db.cursor()
sql = unicode("update t_test_dscgs_svc set dsmc = '福州市A' where cpqs = '闽A'","gb2312")
print sql
cur.execute(sql)
print "update success"
cur.close()

cur = db.cursor()
sql = unicode("insert into t_test_dscgs_svc values ('厦门市','闽D','10000002')","gb2312")
print sql
cur.execute(sql)
print "insert success"
cur.close()
db.close()
 
原创粉丝点击