[英]Connecting to Microsoft SQL server using Python
I am trying to connect to SQL through python to run some queries on some SQL databases on Microsoft SQL server.我正在尝试通过 python 连接到 SQL 以在 Microsoft SQL 服务器上的某些 SQL 数据库上运行一些查询。 From my research online and on this forum the most promising library seems to be pyodbc.
根据我在网上和这个论坛上的研究,最有前途的图书馆似乎是 pyodbc。 So I have made the following code
所以我做了以下代码
import pyodbc
conn = pyodbc.connect(init_string="driver={SQLOLEDB}; server=+ServerName+;
database=+MSQLDatabase+; trusted_connection=true")
cursor = conn.cursor()
and get the following error并得到以下错误
Traceback (most recent call last):
File "C:\Users...\scrap.py", line 3, in <module>
conn = pyodbc.connect(init_string="driver={SQLOLEDB}; server=+ServerName+; database=+MSQLDatabase+; trusted_connection=true")
pyodbc.Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
I have looked at the folowing posts and tried changing my driver to {sql server} and have connected using ODBC links before in SAS, which is partially what my above code is based on, so don't think I need to install anything else.我查看了以下帖子并尝试将我的驱动程序更改为 {sql server} 并在 SAS 中使用 ODBC 链接进行连接,这部分是我上面的代码所基于的,所以不要认为我需要安装任何其他东西。
pyodbc.Error: ('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found, and no default driver specified (0) (SQLDriverConnect)') pyodbc.Error: ('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found, and no default driver specified (0) (SQLDriverConnect)')
Pyodbc - "Data source name not found, and no default driver specified" Pyodbc - “未找到数据源名称,未指定默认驱动程序”
Thanks谢谢
This is how I do it...我就是这样做的...
import pyodbc
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=server_name;"
"Database=db_name;"
"Trusted_Connection=yes;")
cursor = cnxn.cursor()
cursor.execute('SELECT * FROM Table')
for row in cursor:
print('row = %r' % (row,))
Relevant resources:相关资源:
https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-SQL-Server-from-Windows https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-SQL-Server-from-Windows
http://blogs.msdn.com/b/cdndevs/archive/2015/03/11/python-and-data-sql-server-as-a-data-source-for-python-applications.aspx http://blogs.msdn.com/b/cdndevs/archive/2015/03/11/python-and-data-sql-server-as-a-data-source-for-python-applications.aspx
Minor addition to what has been said before.对前面所说的内容做了一点补充。 You likely want to return a dataframe.
您可能想要返回一个数据框。 This would be done as
这将作为
import pypyodbc
import pandas as pd
cnxn = pypyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=server_name;"
"Database=db_name;"
"uid=User;pwd=password")
df = pd.read_sql_query('select * from table', cnxn)
In data source connections between a client and server there are two general types: ODBC which uses a DRIVER and OLEDB which uses a PROVIDER.在客户端和服务器之间的数据源连接中,有两种通用类型:使用 DRIVER 的 ODBC 和使用 PROVIDER 的 OLEDB。 And in the programming world, it is a regular debate as to which route to go in connecting to data sources.
在编程世界中,关于连接数据源的路径是经常性的争论。
You are using a provider, SQLOLEDB
, but specifying it as a driver.您正在使用提供程序
SQLOLEDB
,但将其指定为驱动程序。 As far as I know, neither the pyodbc nor pypyodbc modules support Window OLEDB connections.据我所知,pyodbc 和 pypyodbc 模块都不支持 Window OLEDB 连接。 However, the adodbapi does which uses the Microsoft ADO as an underlying component.
但是, adodbapi使用 Microsoft ADO 作为底层组件。
Below are both approaches for your connection parameters.以下是您的连接参数的两种方法。 Also, I string format your variables as your concatenation did not properly break quotes within string.
另外,我对您的变量进行字符串格式化,因为您的连接没有正确断开字符串中的引号。 You'll notice I double the curly braces since it is needed in connection string and
string.format()
also uses it.您会注意到我将花括号加倍,因为连接字符串中需要它,并且
string.format()
也使用它。
# PROVIDER
import adodbapi
conn = adodbapi.connect("PROVIDER=SQLOLEDB;Data Source={0};Database={1}; \
trusted_connection=yes;UID={2};PWD={3};".format(ServerName,MSQLDatabase,username,password))
cursor = conn.cursor()
# DRIVER
import pyodbc
conn = pyodbc.connect("DRIVER={{SQL Server}};SERVER={0}; database={1}; \
trusted_connection=yes;UID={2};PWD={3}".format(ServerName,MSQLDatabase,username,password))
cursor = conn.cursor()
I Prefer this way ... it was much easier我更喜欢这种方式......这更容易
http://www.pymssql.org/en/stable/pymssql_examples.html http://www.pymssql.org/en/stable/pymssql_examples.html
conn = pymssql.connect("192.168.10.198", "odoo", "secret", "EFACTURA")
cursor = conn.cursor()
cursor.execute('SELECT * FROM usuario')
Following Python code worked for me.以下 Python 代码对我有用。 To check the ODBC connection, I first created a 4 line C# console application as listed below.
为了检查 ODBC 连接,我首先创建了一个 4 行 C# 控制台应用程序,如下所示。
Python Code Python代码
import pandas as pd
import pyodbc
cnxn = pyodbc.connect("Driver={SQL Server};Server=serverName;UID=UserName;PWD=Password;Database=My_DW;")
df = pd.read_sql_query('select TOP 10 * from dbo.Table WHERE Patient_Key > 1000', cnxn)
df.head()
Calling a Stored Procedure调用存储过程
dfProcResult = pd.read_sql_query('exec dbo.usp_GetPatientProfile ?', cnxn, params=['MyParam'] )
C# Program to Check ODBC Connection用于检查 ODBC 连接的 C# 程序
static void Main(string[] args)
{
string connectionString = "Driver={SQL Server};Server=serverName;UID=UserName;PWD=Password;Database=My_DW;";
OdbcConnection cn = new OdbcConnection(connectionString);
cn.Open();
cn.Close();
}
Try using pytds, it works throughout more complexity environment than pyodbc
and more easier to setup.尝试使用 pytds,它可以在比
pyodbc
更复杂的环境中工作,并且更容易设置。
I made it work on Ubuntu 18.04我让它在 Ubuntu 18.04 上运行
Ref: https://github.com/denisenkom/pytds
参考: https ://github.com/denisenkom/pytds
import pytds
with pytds.connect('server', 'database', 'user', 'password') as conn:
with conn.cursor() as cur:
cur.execute("select 1")
cur.fetchall()
Try with pymssql
: pip install pymssql
尝试使用
pymssql
: pip install pymssql
import pymssql
try:
conn = pymssql.connect(server="host_or_ip", user="your_username", password="your_password", database="your_db")
cursor = conn.cursor()
cursor.execute ("SELECT @@VERSION")
row = cursor.fetchone()
print(f"\n\nSERVER VERSION:\n\n{row[0]}")
cursor.close()
conn.close()
except Exception:
print("\nERROR: Unable to connect to the server.")
exit(-1)
Output:输出:
SERVER VERSION:
Microsoft SQL Server 2016 (SP2-CU14) (KB4564903) - 13.0.5830.85 (X64)
Jul 31 2020 18:47:07
Copyright (c) Microsoft Corporation
Standard Edition (64-bit) on Windows Server 2012 R2 Standard 6.3 <X64> (Build 9600: ) (Hypervisor)
The connection can also be checked from the terminal, with a single line of code with sqlcmd
.也可以使用
sqlcmd
的单行代码从终端检查连接。 See syntax .请参阅语法。
╔═════════╦═════════════════════════════════════════╗
║ Command ║ Description ║
╠═════════╬═════════════════════════════════════════╣
║ -S ║ [protocol:]server[instance_name][,port] ║
║ -U ║ login_id ║
║ -p ║ password ║
║ -Q ║ "cmdline query" (and exit) ║
╚═════════╩═════════════════════════════════════════╝
sqlcmd -S "host_or_ip" -U "your_username" -p -Q "SELECT @@VERSION"
output:输出:
Password: your_password
--------------------------------------------------------------------------------------------------------------------------------------------------------
Microsoft SQL Server 2016 (SP2-CU14) (KB4564903) - 13.0.5830.85 (X64)
Jul 31 2020 18:47:07
Copyright (c) Microsoft Corporation
Standard Edition (64-bit) on Windows Server 2012 R2 Standard 6.3 <X64> (Build 9600: ) (Hypervisor)
(1 rows affected)
Network packet size (bytes): 4096
1 xact[s]:
Clock Time (ms.): total 1 avg 1.00 (1000.00 xacts per sec.)
here's the one that works for me:这是对我有用的一个:
from sqlalchemy import create_engine
import urllib
import pandas
conn_str = (
r'Driver=ODBC Driver 13 for SQL Server;'
r'Server=DefinitelyNotProd;'
r'Database=PlayPen;'
r'Trusted_Connection=Yes;')
quoted_conn_str = urllib.parse.quote_plus(conn_str)
engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted_conn_str))
sqlcmd = """select * from information_schema.tables"""
df = pd.read_sql(sqlcmd, engine)
I tried to connect sql server in following ways and those worked for me.我尝试通过以下方式连接 sql server,这些方式对我有用。
To connect using windows authentication使用 Windows 身份验证进行连接
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};Server='+servername+';Trusted_Connection=yes;Database='+databasename+';')
cursor = conn.cursor()
cursor.execute("Select 1 as Data")
To use sql server authentication I used following code.要使用 sql server 身份验证,我使用了以下代码。
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};Server='+servername+ ';UID='+userid+';PWD='+password+';Database='+databasename)
cursor1 = conn.cursor()
cursor1.execute("SELECT 1 AS DATA")
An alternative approach would be installing Microsoft ODBC Driver 13, then replace SQLOLEDB
with ODBC Driver 13 for SQL Server
另一种方法是 安装Microsoft ODBC Driver 13,然后将
SQLOLEDB
替换为ODBC Driver 13 for SQL Server
Regards.问候。
I found up-to-date resources here: Microsoft |我在这里找到了最新的资源: Microsoft | SQL Docs |
SQL 文档 | Python SQL Driver
Python SQL 驱动程序
There are these two options explained including all the prerequisites needed and code examples: Python SQL driver - pyodbc (tested & working) Python SQL driver - pymssql解释了这两个选项,包括所需的所有先决条件和代码示例: Python SQL 驱动程序 - pyodbc (经过测试和工作) Python SQL 驱动程序 - pymssql
My version.我的版本。 Hope it helps.
希望能帮助到你。
import pandas.io.sql
import pyodbc
import sys
server = 'example'
db = 'NORTHWND'
db2 = 'example'
#Crear la conexión
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=' + server +
';DATABASE=' + db +
';DATABASE=' + db2 +
';Trusted_Connection=yes')
#Query db
sql = """SELECT [EmployeeID]
,[LastName]
,[FirstName]
,[Title]
,[TitleOfCourtesy]
,[BirthDate]
,[HireDate]
,[Address]
,[City]
,[Region]
,[PostalCode]
,[Country]
,[HomePhone]
,[Extension]
,[Photo]
,[Notes]
,[ReportsTo]
,[PhotoPath]
FROM [NORTHWND].[dbo].[Employees] """
data_frame = pd.read_sql(sql, conn)
data_frame
This is how I had done it.我就是这样做的。
import pyodbc
connection = pyodbc.connect("DRIVER={SQL Server Native Client 10.0};"
"SERVER=server_name;"
"DATABASE=database_name;"
"UID=user_id_of_database;"
"PWD=password_of_database;")
cursor = connection.cursor()
cursor.execute('SELECT * FROM Table')
Always make sure you had specified the correct Driver.始终确保您指定了正确的驱动程序。 You can check your Driver by following the steps given below.
您可以按照以下步骤检查您的驱动程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.