Thursday, February 21, 2019

py0014: table_name1 = table_name.replace(',','') AttributeError: 'pyodbc.Row' object has no attribute 'replace'

Problem :
below is my sample code, where i am getting error table_name1 = table_name.replace(',','') AttributeError: 'pyodbc.Row' object has no attribute 'replace' and in same example you can cover how to use replace in python
    cursor.execute('select table_name from information_schema.tables')
    for table_name in cursor:
        table_name1 = table_name.replace(',','')
        print (table_name1)

I was trying to loop the list of all table names which are in schema using query "select table_name from information_schema.tables". The intention was to do some action based on the table exists or not.

Why i used replace:
suppose after for loop when i use command "print (table_name)", it gives output enclosed in single quotes and postfix by comma, so i used replace function to replace comma and it starts throwing above error.

Solution:
if you notice code above i gave "table_name" in for loop and for replace function we have to write it as str.replace(old,new). But in my case replace was not able to get any string in "table_name" because "table_name" is just act as "i" here in for loop and it is not a attribute in this situation.

So i have to use "table_name.table_name.replace(',','')"

Correct code as below:
    cursor.execute('select table_name from intermediate_table')
    for tb in cursor:

        table_name1 = tb.table_name.replace(',','')
        print (table_name1)

Here i have replace table_name in for loop with "tb" for better visibilty and better understanding.

No comments:

Post a Comment

web stats