store sql result in a variable in python

I need help in storing the query result in a variable after executing the select statement. this is my code below.. there are no error but i need help in storing it in a variable in PYTHON. i am using pymssql and python 2.7.9. thanks in advance

First of all, c.fetchall() retrieves ALL the results from your query, we'll put them in a variable called rows. Then we create a iterator (the thing you tried to do with the while loop) by doing for row in rows. Then we simply print each row.

This opens a context handle called conn which will automatically close the connection when you're done with your code (leaving no open connections which could be a problem) and secondly it's less code iterating directly over c.fetchall() and potentially be faster if the function supports iterations, which it probably will in later versions.

Here's one where you just add upp all the results into a hughe string (for dumping out to a file etc for instance). Note that this might fill your memory if the results are many, sequentially storing this to the file in such a case would be better, hence why you normally work with each database row individually for memory reasons.