pandas 如何通过python anaconda jupyter连接到Azure sql数据库

cwdobuhd  于 2023-01-19  发布在  Python
关注(0)|答案(2)|浏览(136)

我试图通过Jupyter笔记本连接到Azure SQL数据库,稍后将数据加载到Excel/csv中。我只有服务器和数据库的详细信息。用户名和密码,我认为默认情况下,它需要我的桌面凭据(不确定)。
下面是试用代码

import pyodbc 
cnxn = pyodbc.connect(Server=myserver;Database=mydatabase)
7ajki6be

7ajki6be1#

要使用jupyter笔记本连接到Azure SQL数据库,请使用以下命令:

import pyodbc

server = 'tcp:SQLSERVER.database.windows.net' # Server example
database = '<INSERT DATABASE NAME>' 
username = '<INSERT USERNAME>' 
password = '<INSER PASSWORD>' 
driver= '{ODBC Driver 17 for SQL Server}' # Driver example
connection= pyodbc.connect('DRIVER=' + driver + ';SERVER=' +server + ';PORT=1433;DATABASE=' + database +';UID=' + username + ';PWD=' + password)

cursor = connection.cursor() # Just something you can do
print(connection)
connection.close()

有关详细信息,请参阅以下链接:

  1. Connect to Azure SQL Database using Python and Jupyter Notebook
  2. Connect to Azure SQL Database in a Jupyter Notebook using Python
  3. Quickstart: Use Python to query a database
rqqzpn5f

rqqzpn5f2#

你需要在connextion中给予Azure SQL数据库的用户名和密码。下面是在Jupyter Notebook中使用python建立Azure SQL数据库连接的代码。

import pyodbc
# Establish the connection
server =  'xxxxx.database.windows.net'
database =  'xxx'
username =  'xxxx'
password =  'xxxx'
driver=  '{ODBC Driver 17 for SQL Server}'
conn = pyodbc.connect('DRIVER='  + driver +  ';SERVER='  +
server +  ';PORT=1433;DATABASE='  + database +
';UID='  + username +  ';PWD='  + password)
print(conn)
conn.close()

参考:Use Python to query a database - Azure SQL Database & SQL Managed Instance | Microsoft Learn

相关问题