Advertisement
johnmahugu

python odb test

May 6th, 2016
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.16 KB | None | 0 0
  1. # Example of using pyodbc to connect to server, fetch data,
  2. # and return it as JSON or print to screen
  3.  
  4. # module import
  5. import pyodbc
  6. import json
  7.  
  8. # server-specific connection string
  9. connstr = 'DRIVER={SQL Server};SERVER=ServerName;DATABASE=Test;'
  10.  
  11. # use pyodbc's "connect" method to establish the connection
  12. conn = pyodbc.connect(connstr)
  13.  
  14. # create a cursor object using the connection's "cursor" method
  15. cursor = conn.cursor()
  16.  
  17. # two variables to limit the query
  18. fname = 'Bob'
  19. lname = 'Jones'
  20.  
  21. # execute the query, passing in the variables
  22. cursor.execute("""
  23.            SELECT ID, LastName, FirstName
  24.            FROM Employees
  25.            WHERE LastName = ? AND FirstName = ?
  26.            """, lname, fname)
  27.  
  28. # the variable "rows" contains every row fetched
  29. rows = cursor.fetchall()
  30.  
  31. # now, build a list of lists to output to JSON
  32. outlist = []
  33. for row in rows:
  34.     l = [row.FirstName, row.LastName, str(row.ID)]  
  35.     outlist.append(l)
  36.     #print row.FirstName + ' ' + row.LastName + ', ID: ' + str(row.ID)
  37.  
  38. # dump the list to JSON and print to screen.
  39. j = json.dumps(outlist)
  40. print j
  41.  
  42. # close the connection to the server
  43. conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement