Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Server query with python

I need to know how to query a table in sql server. Everywhere i look it says to use pyodbc but they didn't make one for 3.4 .

like image 800
Ninety3cents Avatar asked Feb 12 '23 02:02

Ninety3cents


1 Answers

There isn't an official pyodbc for Python 3.4. However, as bernie mentions in his comment, you can try the 3.3 version. Additionally, the University of California, Irvine provides an unofficial build for pyodbc for Python 3.4. There is also the pypyodbc package, as an option.

In any case, once you decide on which to utilize, you can use it by doing something like this. Realize this a very simple query.

import pyodbc
# Create connection
con = pyodbc.connect(driver="{SQL Server}",server=SERVERNAME,database=DATA_BASE_INFO,uid=username,pwd=password)
cur = con.cursor()
db_cmd = "SELECT * FROM table_name"
res = cur.execute(db_cmd)
# Do something with your result set, for example print out all the results:
for r in res:
    print r

In the line that beings con =, there are several values for you to fill in.

  • server needs to be server host information (either IP or DNS name), and possibly a port (default is 1435) "dns.to.host.com,1435"
  • uid is the username you are logging in with
  • pwd is the password of the user you are logging in with
like image 105
Andy Avatar answered Feb 14 '23 18:02

Andy