Home > Back-end >  Python pyodbc loop - remove brackets, hyphens and commas from list
Python pyodbc loop - remove brackets, hyphens and commas from list

Time:07-19

I'm using the below Python script to loop around a SQL Server table and save the values to a list. However, I don't want the brackets \ commas etc. When I run the below the records in the list look like this:

('TN12345', )

I just want the below - how it exists in the SQL table:

TN12345

This is my script:

import pyodbc

connstr = 'DRIVER={SQL Server};SERVER=XXXXXXXXXXX;DATABASE=XXXXXXXXXXX;Trusted_Connection=yes;'
conn = pyodbc.connect(connstr)
cursor = conn.cursor()

cursor.execute("""SELECT TN_Number FROM Table""")

records = cursor.fetchall()
insertObject = []
columnNames = [column[0] for column in cursor.description]

for record in records:
    insertObject.append( dict( zip( columnNames , record ) ) )

for i in range(len(records)):
  print(records[i])

CodePudding user response:

This

('TN12345', )

is tuple with one element, representing row in database, if you can guarantee that your query will always return exactly 1 column then you might use [0] to access single element in said tuple, in your case replace

for i in range(len(records)):
  print(records[i])

using

for i in range(len(records)):
  print(records[i][0])

alternatively you might use for loop directly (without caring about index) in following way

for record in records:
  print(record[0])

CodePudding user response:

If you want to get all elements one by one in your tuples:

for i in range(len(records)):
    for j in records[i]:
        print(j)

Advantage is it will return every entry in your tuples no matter the length of the tuple or the length of the list of tuples.

  • Related