python 连接mysql数据库

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import MySQLdb


reload(sys)
sys.setdefaultencoding('utf-8')


db=MySQLdb.connect("服务器ip","username","password","database",charset='utf8')
cursor=db.cursor()
cursor.execute("select * from table limit 1")
data=cursor.fetchone()
print data


db.close()


注意:

1.打印出来的data是元祖类型(A,B,C)

2.如果其中有中文,打印出来的数据中会限制unicode编码,使用print data[索引值]的方式打印出来就是中文了

3.fetchone表示从上面查询语句的结果中,返回单个元祖,即第一条记录,如果没有值,就返回None

4.与fetchone对应的还有一个fetchall函数,返回二维元祖,((元祖1),(元祖2)...)

猜你喜欢

转载自blog.csdn.net/waiwai3/article/details/79061048