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?
The syntax to establish a connection between the Python and SQL Server using the pyodbc is as shown below Driver: Here, you have to specify the ODBC Connection or SQL Server Native Client. Server: You have to specify the server instance name. Database Name: You have to specify the database name from where you want to extract the data.
Once you established such a connection between Python and SQL Server, you can start using SQL in Python to manage your data. You can also use Python to insert values into SQL Server table . For further information about the pyodbc package, please visit the pyodbc documentation .
And it has all the required functions to set up a connection with SQL Server from Python IDE. If you don’t have the Python library, then open the command prompt as Administrator, then navigate to Python scripts (optional), and type pip install pyodbc.
My Python installed through Anaconda already came with necessary libraries built-in, so there’s no need for additional installations. To connect from Python, I’ll use mysql library: Once you execute this block of code you will get this as an output: 3 down, 1 to go!
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With