0

I have a function to grab info from mysql database:

def get_group_members_from_db():
    dbName = get_environ('DBNAME')
    # Establish connection to database
    try:
        db = db_establish_connection()
        if db:
            # report count sessions by role, agent version, agent type, and realm
            sql = (
                'SELECT T1.field1, T1.field2, T1.field3, T1.field4, T1.field5 ' 
                'FROM ' + dbName + '.table AS T1 ' 
                'GROUP BY T1.field1, T1.field2, T1.field3, T1.field4, T1.field5; '
            )
            cursor = db.cursor()
            cursor.execute(sql)
            result = cursor.fetchall()
            cursor.close()
            db.disconnect()
            #print(result)
            return result
    except Exception as ex:
        print(ex)

and another function that is inserting into a new table into the database:

def finding_unique_users(db,dbName):
    # Establish connection to database
    try:
        users = get_group_members_from_db()
        if db:
            # report count sessions by role, agent version, agent type, and realm
            sql = (
                
                'INSERT INTO ' + dbName + ' .table2 ( '
                'fieldA, fieldB, fieldC, fieldD, fieldE, fieldF ) ' 
                'VALUES ('
                '%s,%s,%s,%s,%s);'
            )
            values = list()
            for user in users:
                #print(users)
                if user['fieldA']:
                    values.append((
                        user['fieldA'],
                        user['fieldB'],
                        user['fieldC'],
                        user['fieldD'],
                        user['fieldE'],
                        user['fieldF']
                    ))
            cursor = db.cursor()
            cursor.execute('TRUNCATE TABLE ' + dbName + '.table2;')
            cursor.executemany(sql,values)
            db.commit()
            result = cursor.fetchall()
            cursor.close()
            return result
    except Exception as ex:
        print(ex)

When I am running I run into an error that says tuple indices must be integers or slices, not str. When I print out the users from database, I am receiving a tuple back. Please help me further to correct this error.

Nikki
  • 1
  • 1
  • 1
  • Does this answer your question? [Python, MySQL and SELECT output to dictionary with column names for keys](https://stackoverflow.com/questions/7268178/python-mysql-and-select-output-to-dictionary-with-column-names-for-keys) You can't access `user['fieldA']` because `user` is a tuple, you need to get the users as a dict (the question linked) or access the fields by index – Iain Shelvington Jun 25 '21 at 02:31

2 Answers2

0

Function fetchall return a list if tuple where 1st item is the column Bâle and 2nd item is the value If you prefer to have a list if dict, you can construct it

res= cursor.fetchall()
cursor.close()
result = []
for raw in res:
   result.append({raw[0] : raw[1})
return result
DonKnacki
  • 427
  • 4
  • 11
0

I do not have access to the stack trace but I assume the problem occurs at the user['fieldA'] line. The user variable is a tuple which means it cannot be accessed by field names unlike dictionary. You can access different indexes of the tuple either by an integer index (like user[0]) or by a slice (like user[0:2]), string indexes like user['fieldA'] do not work on a tuple.

A.S
  • 11
  • 4