Thursday, December 9, 2010

Read a SQL Server table into a list using Python + pyodbc

import pyodbc as p
server = 'ServerName'
database = 'DatabaseName'
userid = 'UserName'
pwd = 'UserPassword'

connStr = ( r'DRIVER={SQL Server};SERVER=' +
            server + ';DATABASE=' + database + ';' +
            'UID=' + userid + ';PWD='+pwd+';')        
lst = []
conn = p.connect(connStr)
dbCursor = conn.cursor()
sql = ('SELECT ColumnName AS FieldValue FROM tblTableName') 
dbCursor = conn.cursor()
dbCursor.execute(sql)
for row in dbCursor:
    lst.append(row.FieldValue)        
conn.close()
print lst

No comments:

Post a Comment