8

I'd like to connect from IPython notebook to a SQL-Server database via integrated security.

Is this possible? I'm guessing yes it is.

How do I format the connection string in the following?

import pandas as pd
import pandas.io.sql as psql
sql = "SELECT * FROM WHdb.dbo.vw_smallTable"
cnx = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=WHdb;Data Source=OurServerName"
data = psql.read_sql(sql, cnx)

This just gives an error. Am I going about the cnx incorrectly?

Thomas K
  • 39,200
  • 7
  • 84
  • 86
whytheq
  • 34,466
  • 65
  • 172
  • 267
  • 1
    Please post the full error – kylieCatt Mar 15 '16 at 20:28
  • @IanAuld had to step away from the work machine (to sleep!) - I'll add the msg tomorrow. On the face of it does it look ok? Am I correct using a string in that way as the second argument of `read_sql`? – whytheq Mar 15 '16 at 21:18
  • I doubt I'll be much help as I've never used SQLServer with Python. However this question as written falls squarely in to the "What isn't this code working?" close reason. I won't vote to close but it does run the risk of being closed as is – kylieCatt Mar 15 '16 at 23:10
  • @IanAuld I hope this helps me - will try tomorrow: http://stackoverflow.com/questions/16515420/connecting-to-ms-sql-server-with-windows-authentication-using-python – whytheq Mar 15 '16 at 23:24

2 Answers2

10

You need to install the package, pypyodbc

!pip install pypyodbc

Then, you can import it as follows:

import pypyodbc as podbc

You can now create the connection:

conn = podbc.connect("Driver={SQL Server};Server=<YourServer>;Database=<YourDatabase>;uid=<YourUserName>;pwd=<YourPassword>"

Finally, you fetch your data as follows:

cursor = conn.cursor()
sql = "SELECT * FROM WHdb.dbo.vw_smallTable"
cursor.execute(sql)
data = cursor.fetchone()
while data:
    print(str(data[0]) + ", " + ... + ", " + str(data[n-1]))
    data = cursor.fetchone()
conn.close()

Note that n = number of columns in your table.

user7110627
  • 116
  • 2
  • 4
1

This is what worked for me well...

import pyodbc

server = 'myserver'

database = 'mydb'

username = 'myusername'

password = 'mypassword'



#Connection String

connection = pyodbc.connect('DRIVER={SQL Server Native Client 11.0};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)

cursor = connection.cursor()



#Sample select query

cursor.execute("SELECT @@version;")

row = cursor.fetchone()

while row:

    print row[0]

    row = cursor.fetchone()
loveR
  • 489
  • 4
  • 12