python fetching row by row from MySQL

来源:互联网 发布:java合并list 编辑:程序博客网 时间:2024/06/06 17:27

Fetching row by row from MySQL in Python

2013-09-08T02:51:46+05:30 on Python

Writing this post as a note to myself. Many times we want to fetch records from MySQL row by row. We try to do that by the following code

import MySQLdbconn = MySQLdb.connect(user="user", passwd="password", db="dbname")cur = conn.cursor()cur.execute("SELECT id, name FROM students")row = cur.fetchone()while row is not None:    print row[0], row[1]    row = cur.fetchone()cur.close()conn.close()

But remember that the default cursor fetches all data at once from the server, it does not matter that if you use fetchall or fetchone.

You have to use a different cursor which supports server side resultsets, likeSSCursor or SSDictCursor.

import MySQLdbimport MySQLdb.cursorsconn = MySQLdb.connect(user="user", passwd="password", db="dbname",                        cursorclass = MySQLdb.cursors.SSCursor)cur = conn.cursor()cur.execute("SELECT id, name FROM students")row = cur.fetchone()while row is not None:    print row[0], row[1]    row = cur.fetchone()cur.close()conn.close()
出处:https://kushaldas.in/posts/fetching-row-by-row-from-mysql-in-python.html
原创粉丝点击