Extracting Values from MSSQL using pyodbc

时间:2017-07-10 15:30:34

标签: python sql-server unicode pyodbc

I am new to Python and I am having a difficulty in reading values from a column in MSSQL into a list. The output has a text u' for each value and the encode function is not working to remove the same

For example, if column name = 'Cities" and Table Name = "World City"- when I execute the attached code, I get the output as below

Actual Output: [(u'chicago', ),(u'dallas', ),(u'kansas', )] Expected Output: [chicago,dallas,kansas]

import pyodbc
def colread(columnname,tablename,listname):
    cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                  "Server= ABC;"
                  "Database=City;"
                  "Trusted_Connection=yes;")

    cursor = cnxn.cursor()
    sql = "SELECT " + columnname + " FROM " + tablename
    cursor.execute(sql)
    data = cursor.fetchall()
    columnlist = []
    listname = []

    for row in data:
       c = row
       columnlist.append(c)
    columnlist = [item for item in columnlist if item]
    listname = columnlist
    listname = [item.encode('ascii','ignore') for item in columnlist]
    cnxn.close()
    return listname
 CITYDB = colread('Cities','World_City','citydb')
 print  CITYDB[0:10]

Note: I learnt about the SQL injection issue which I would solve once I resolve this issue.

1 个答案:

答案 0 :(得分:1)

您的数据是一元组的。您应该可以这样做以获得所需格式的数据:

columnlist = [item[0] for item in columnlist if item]

如果您对程序有信任输入,则可以动态提供您正在执行的列名和表名。