复制代码 代码如下:
MySQLdb.connect(
host=host,
user=user,
passwd=passwd,
db=db,
port=port,
charset='utf8'
)
查询数据:
复制代码 代码如下:
cur = conn.cursor()
cur.execute('select b_id from blog limit 1')data = cur.fetchall()
cur.close()
conn.close()
打印:
复制代码 代码如下:
for row in data:
print type(row)
print row
执行结果:
复制代码 代码如下:
<type 'tuple'>
(1L,)
为tuple类型。
我们可以这么干使得数据查询结果返回字典类型,即 字段=数据导入模块
复制代码 代码如下:
import MySQLdb.cursors
在连接函数里加上这个参数 cursorclass = MySQLdb.cursors.DictCursor 如:
复制代码 代码如下:
MySQLdb.connect(
host=host,
user=user,
passwd=passwd,
db=db,
port=port,
charset='utf8',
cursorclass = MySQLdb.cursors.DictCursor
)
再重新运行脚本,看看执行结果:
复制代码 代码如下:
<type 'dict'>
{'b_id': 1L}
搞定!
注意,在连接的时候port如果要指定则值必须是整型,否则会出错!
L代表long数据类型,可以有表示无限大的数普通的整数是int类型,对应于C语言中的long类型,有固定的位数
Python3合并了long和int类型,int类型就可以表示无限大的数
在Python2中MySQLdb把所有的数都转换成了long类型
两者在很大的数间进行运算时,可能存在速度的差异,并没有什么其他的影响
如果数小于32位,int()可以把long类型转换为int类型
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)