@@ -1264,6 +1264,34 @@ static PyObject* Cursor_fetch(Cursor* cur)
12641264 apValues[i] = value;
12651265 }
12661266
1267+ // Return a dict instead of a Row if so requested.
1268+ // See https://github.com/mkleehammer/pyodbc/issues/171,
1269+ if (cur->rows_as_dicts )
1270+ {
1271+ PyObject* dict = PyDict_New ();
1272+ if (!dict)
1273+ {
1274+ FreeRowValues (field_count, apValues);
1275+ return 0 ;
1276+ }
1277+
1278+ PyObject* name;
1279+ PyObject* index;
1280+ Py_ssize_t pos = 0 ;
1281+ while (PyDict_Next (cur->map_name_to_index , &pos, &name, &index))
1282+ {
1283+ Py_ssize_t i = PyNumber_AsSsize_t (index, PyExc_IndexError);
1284+ if (PyDict_SetItem (dict, name, apValues[i]) == -1 )
1285+ {
1286+ Py_DECREF (dict);
1287+ FreeRowValues (field_count, apValues);
1288+ return 0 ;
1289+ }
1290+ }
1291+ FreeRowValues (field_count, apValues);
1292+ return dict;
1293+ }
1294+
12671295 return (PyObject*)Row_InternalNew (cur->description , cur->map_name_to_index , field_count, apValues);
12681296}
12691297
@@ -2481,6 +2509,8 @@ static char messages_doc[] =
24812509 " This read-only attribute is a list of all the diagnostic messages in the\n " \
24822510 " current result set." ;
24832511
2512+ static char rowsasdicts_doc[] = " If True, rows are returned as dicts instead of Row objects." ;
2513+
24842514static PyMemberDef Cursor_members[] =
24852515{
24862516 {" rowcount" , T_INT , offsetof (Cursor, rowcount), READONLY , rowcount_doc },
@@ -2489,6 +2519,7 @@ static PyMemberDef Cursor_members[] =
24892519 {" connection" , T_OBJECT_EX , offsetof (Cursor, cnxn), READONLY , connection_doc },
24902520 {" fast_executemany" ,T_BOOL , offsetof (Cursor, fastexecmany), 0 , fastexecmany_doc },
24912521 {" messages" , T_OBJECT_EX , offsetof (Cursor, messages), READONLY , messages_doc },
2522+ {" rows_as_dicts" , T_BOOL , offsetof (Cursor, rows_as_dicts), 0 , rowsasdicts_doc },
24922523 { 0 }
24932524};
24942525
@@ -2792,6 +2823,7 @@ Cursor_New(Connection* cnxn)
27922823 cur->rowcount = -1 ;
27932824 cur->map_name_to_index = 0 ;
27942825 cur->fastexecmany = 0 ;
2826+ cur->rows_as_dicts = 0 ;
27952827 cur->messages = Py_None;
27962828
27972829 Py_INCREF (cnxn);
0 commit comments