简体   繁体   English

从Python连接到SQL Server

[英]Connecting from Python to SQL Server

I'd like to connect from IPython notebook to a SQL-Server database via integrated security. 我想通过集成的安全性从IPython Notebook连接到SQL-Server数据库。

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? 我会错误地处理cnx吗?

You need to install the package, pypyodbc 您需要安装软件包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. 请注意,n =表中的列数。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM