get column names from query result using pymssql - python

Is there any way to get the column names from the pymssql results? If i specify as_dict=True I get back a dictionary, which does contain all the column headers, but since it is a dictionary they are not ordered.

pymssql claims to support the Python DB-API, so you should be able to get the .description attribute from your cursor object.
.description
This read-only attribute is a sequence of 7-item
sequences.
Each of these sequences contains information describing
one result column:
(name,
type_code,
display_size,
internal_size,
precision,
scale,
null_ok)
So, the first item in each of the "inner" sequences is the name for each column.

You can create a list of ordered column names using list comprehension on the cursor description attribute:
column_names = [item[0] for item in cursor.description]

To get the column names on a single comma separated line.
colNames = ""
for i in range(len(cursor.description)):
desc = cursor.description[i]
if i == 0:
colNames = str(desc[0])
else:
colNames += ',' + str(desc[0])
print colNames
Alternatively, pass the column names to a list and use .join to get them as string.
colNameList = []
for i in range(len(cursor.description)):
desc = cursor.description[i]
colNameList.append(desc[0])
colNames = ','.join(colNameList)
print colNames

It's a basic solution and need optimizing but the below example returns both column header and column value in a list.
import pymssql
def return_mssql_dict(sql):
try:
con = pymssql.connect(server, user, password, database_name)
cur = con.cursor()
cur.execute(sql)
def return_dict_pair(row_item):
return_dict = {}
for column_name, row in zip(cur.description, row_item):
return_dict[column_name[0]] = row
return return_dict
return_list = []
for row in cur:
row_item = return_dict_pair(row)
return_list.append(row_item)
con.close()
return return_list
except Exception, e:
print '%s' % (e)

Related

How to check if rows in postgresql table and list in python are matching or does contain same files?

import psycopg2
conn = psycopg2.connect("dbname=mydatabase user=myuser password=mypassword")
cur = conn.cursor()
files_name = ["file_789", "file_456", "file_555", "file_111"]
sql = "SELECT filename FROM xml_job WHERE filename IN %s"
cur.execute(sql, (tuple(files_name),))
matching_files = cur.fetchall()
matching_files = [f[0] for f in matching_files]
print(matching_files)
cur.close()
conn.close()
This is my current code. It gives me this output:
[("file_555",), ("file_111",)] # output
My postgresql table has two rows: one named 'filename' and other one 'remarks'
I want my output to be like:
[("file_555","remark1"), ("file_111","remark2")] # output
I dont have your db, so just gonna pencil in what you probably ought to do.
But for the rest, you can use this to find matches and pull out remarks. Note that the order gets changed, but you could easily sort it again.
files_name = ["file_789", "file_456", "file_555", "file_111"]
# adjust your db stuff probably as follows:
#sql = "SELECT filename, remark FROM xml_job WHERE filename IN %s"
#matching_files = [(f[0],f[1]) for f in matching_files]
rows = [("file_555","R1"), ("file_111",'R2')]
#build a dict associating filename and remark.
di = {tu[0]:tu[1] for tu in rows}
#use set operators to find matches
matches = set(files_name) & di.keys()
#now pull the remark from the dictionary you built.
res = [(name,di[name]) for name in matches]
print(res)
output:
[('file_111', 'R2'), ('file_555', 'R1')]
Also, rather than addressing fields with the obscure f[0], f[1] index-based notation, there is something called cursor.description nthat is an array, that has among other things, a field giving the name of the column, and another its index. Sorry, use sqlalchemy myself, but I have used this in the past, much easier to read code when you can see the column names.

Create dictionary from mysql AttributeError: 'tuple' object has no attribute 'name'

Trying to create a dictionary from a mysql database using two columns and then assign it a variable keep getting the traceback AttributeError: 'tuple' object has no attribute 'name'.
cursor = conn.cursor()
cursor.execute("select server_id, name from servers")
dict = {}
for row in cursor:
dict[row.server_id] = row.name
print(dict)
Rows are tuples, not objects with named attributes per column. In your case, name is the value at index 1, the server_id the value at index 0:
d = {}
for row in cursor:
d[row[0]] = row[1]
print(d)
You could make this easier on yourself by using tuple assignments:
d = {}
for server_id, name in cursor:
d[server_id] = name
print(d)
However, because you want to use the first element as the key, and the second as the value, you could make this even simpler and just pass the cursor directly to a dict() call:
d = dict(cursor)
This pulls in each (server_id, name) tuple and turns it into a key and value pair in a new dictionary.
Note that I deliberately used the name d for the dictionary in the above examples. Had I used dict instead, then we couldn't use dict(cursor) anymore!
row in your case is tuple (server_id, name), that's why calling row.name won't work - tuples don't support named attributes. Try row[0] and row[1] instead or unpack tuple:
d = {}
for row in cursor:
server_id, name = row
d[server_id] = name
print(d)

Creating a list of values that are not null

Im trying to save three values from SQLite in a Python list. All values are from a different column but in the same row. If the value is null I dont want to add it to the list. This is the code I wrote:
def create_list(self, chat):
list = []
for x in range(1, 3):
column_name = "list" + str(x)
value = c.execute("SELECT (?) FROM user WHERE (?) NOTNULL AND id = (?)", (column_name, column_name, chat)).fetchall()
if value != None:
list.append(value[0][0])
print(list)
Instead of printing the SQLite values in a list it just prints: ['list1', 'list2', 'list3'] (If one of the values in the table is null it doesnt print that one. For example if the value in column liste3 is null it just prints ['list1', 'list2'])
How can I fix this so that it saves the actual SQLite values in the list?
I had the same problem.
SQLite package ignores NULL values by default after fetching the data. you need to put a condition that prints 'Empty' or something when it faces NULL values. something like:
conn = sqlite3.connect("someDataBase.db")
db = conn.cursor()
db.execute('''
SELECT name, email
FROM person
WHERE name = 'some dude'
''')
result = db.fetchone()
if result is None: #if a value IS NULL
print 'Empty'
else:
var = result[0]
print var

How do i keep the order of my SQL columns in Python when saving?

If you scroll down a bit you can see this code from g.d.d.c return SQL table as JSON in python:
qry = "Select Id, Name, Artist, Album From MP3s Order By Name, Artist"
# Assumes conn is a database connection.
cursor = conn.cursor()
cursor.execute(qry)
rows = [x for x in cursor]
cols = [x[0] for x in cursor.description]
songs = []
for row in rows:
song = {}
for prop, val in zip(cols, row):
song[prop] = val
songs.append(song)
# Create a string representation of your array of songs.
songsJSON = json.dumps(songs)
I just want to keep the order of my columns.
For example when I print(cols) I get this:
['id', 'Color', 'YCoord', 'Width', 'Height'] # right order
But the columns are saved in a wrong order:
[{"Color": "#FF99FF","Width"=345, "id"=43, "YCoord"=5784 "Height"=-546}...] # wrong order
The more columns I add, the more random it gets.
Python dict don't save the order of keys, use OrderedDict instead.
If I understand You want dictionary to have ordered key. It's not possible, because dictionaries are not keeping keys in some order, because keys are used only to access elements. You can always print columns of data using raw column information:
cols = ["column1", "column2", "column3"]
for row in data_from_database:
for col in cols:
print row[col]

How to retrieve SQL result column value using column name in Python using MySql data base?

Is there a way to retrieve SQL result column value using column name instead of column index in Python?
result = `select name, deptname from employee;`
I tried below one:
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT name, category FROM animal")
result_set = cursor.fetchall()
for row in result_set:
print "%s, %s" % (row["name"], row["deptname"])
Here I got an error like:
TypeError: tuple indices must be integers, not str
Any help will be awesome?
Actually you are getting what you wanted.
You just need to use the row not as a dictionary but as a tuple.
That means that the indices are numbers, not strings.
Try
print "%s, %s" % (row[0], row[1])
instead
You are not correctly specifying that you need a dictionary cursor. Do that when you call the connect() method, set the cursorclass:
import MySQLdb
conn = MySQLdb.connect(user='user',
passwd='password',
db='db_name',
cursorclass=MySQLdb.cursors.DictCursor)
cursor = conn.cursor()

Categories