gpt4 book ai didi

sql-server - 从 Python 连接到 SQL Server

转载 作者:行者123 更新时间:2023-12-02 22:46:45 25 4
gpt4 key购买 nike

我想通过集成安全性从 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的理解是否错误?

最佳答案

您需要安装软件包 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 = 表格中的列数。

关于sql-server - 从 Python 连接到 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36021385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com