【问题标题】:Connecting from Python to SQL Server从 Python 连接到 SQL Server
【发布时间】:2016-07-01 11:44:31
【问题描述】:

我想通过集成安全性从 IPython 笔记本连接到 SQL-Server 数据库。

这可能吗?我猜是的。

如何格式化下面的连接字符串?

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)

这只是给出一个错误。 我是否错误地处理了cnx

【问题讨论】:

  • 请发布完整的错误
  • @IanAuld 不得不离开工作机器(睡觉!) - 我明天会添加味精。表面上看起来还好吗?我以这种方式使用字符串作为read_sql 的第二个参数是否正确?
  • 我怀疑我会不会有很大帮助,因为我从来没有在 Python 中使用过 SQLServer。然而,所写的这个问题完全属于“这段代码不起作用?”关闭的原因。我不会投票关闭,但它确实有被关闭的风险
  • @IanAuld 我希望这对我有帮助 - 明天试试:stackoverflow.com/questions/16515420/…

标签: sql-server python-3.x pandas ipython jupyter-notebook


【解决方案1】:

你需要安装包,pypyodbc

!pip install pypyodbc

然后,你可以按如下方式导入:

import pypyodbc as podbc

您现在可以创建连接:

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

最后,您按如下方式获取数据:

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

请注意,n = 表格中的列数。

【讨论】:

    【解决方案2】:

    这对我很有效......

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 2014-12-25
      • 2014-02-09
      • 2011-03-30
      • 1970-01-01
      相关资源
      最近更新 更多