Saya mencoba menyambung ke SQL melalui python untuk menjalankan beberapa kueri pada beberapa database SQL di server Microsoft SQL. Dari penelitian saya secara online dan di forum ini perpustakaan yang paling menjanjikan tampaknya adalah pyodbc. Jadi saya telah membuat kode berikut
import pyodbc
conn = pyodbc.connect(init_string="driver={SQLOLEDB}; server=+ServerName+;
database=+MSQLDatabase+; trusted_connection=true")
cursor = conn.cursor()
dan dapatkan error berikut
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.
Pyodbc - "Data source name not found, and no default driver specified"
Thanks
adodbapi
to use OLEDB connection. And string format is the recommended way to pass variables into a string rather than using the+
operator. The curly braces with numbers are placeholders whichformat()
fills in accordingly. You can even pass in lists and tuples usingformat()
. Your original code did not break string and variables by quotes, so+
was considered part of string.I Prefer this way ... it was much easier
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')
sumber
Here are some pics for newbies.
sumber
Try using pytds, it works throughout more complexity environment than
pyodbc
and more easier to setup.I made it work on Ubuntu 18.04
Example code in documentation:
import pytds with pytds.connect('server', 'database', 'user', 'password') as conn: with conn.cursor() as cur: cur.execute("select 1") cur.fetchall()
sumber
Following Python code worked for me. To check the ODBC connection, I first created a 4 line C# console application as listed below.
Python Code
import pandas as pd import pyodbc cnxn = pyodbc.connect("Driver={SQL Server};Server=serverName;UID=UserName;PWD=Password;Database=RCO_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
static void Main(string[] args) { string connectionString = "Driver={SQL Server};Server=serverName;UID=UserName;PWD=Password;Database=RCO_DW;"; OdbcConnection cn = new OdbcConnection(connectionString); cn.Open(); cn.Close(); }
sumber
An alternative approach would be installing Microsoft ODBC Driver 13, then replace
SQLOLEDB
withODBC Driver 13 for SQL Server
Regards.
sumber
here's the one that works for me:
from sqlalchemy import create_engine import urllib 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))
sumber
I found up-to-date resources here: Microsoft | SQL Docs | Python SQL Driver
There are these two options explained including all the prerequisites needed and code examples: Python SQL driver - pyodbc (tested & working) Python SQL driver - pymssql
sumber
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
sumber
I tried to connect sql server in following ways and those worked for me.
To connect using windows authentication
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.
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")
sumber
Try with
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:
The connection can also be checked from the terminal, with a single line of code with
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:
sumber