Python connect to database sql server

KAILASH’S BLOGS

‘Kailash’s Blogs’ is for sharing my experience and ideas about different aspects of the technologies in the software world.

Pages

Python Connect to SQL Database

Introduction

This blog Python Connect to SQL Database will guide to connect Microsoft SQL Server database in Python using pyodbc package. Here we will connect the local SQL server with windows authentication and remote SQL server with user credentials. We will also discuss the connection string example to connect Azure Active Directory.

Python Connect to SQL Database

Getting Started

Python library provides pyodbc package to connect Microsoft SQL Server database. The pyodbc database is open source and is available in python portal.If your machine does not have pyodbc, efer my previous blog How to install pyodbc window to install pyodbc package.

Читайте также:  Database Records

The pyodbc introduced a connection method to connect to the Microsoft SQL Server database and it accepts string variable as a parameter. The string variable should contain like below value.

Python Connect to SQL Database

SQL Windows Authentication

 'DRIVER=;SERVER=Database Server Name;DATABASE=Database Name;Trusted_Connection=yes;' 

SQL Server Authentication

 'DRIVER=;SERVER=Database Server Name;DATABASE=Database Name;UID=sa;PWD=XXXXXX' 

Above both are the connection strings to establish connection to Microsoft SQL Server. In below we will see the example of connection strings.

Pyodbc ConnectionString Examples

SQL Windows Authentication

 'Driver=;Server=DESKTOP-SQQV4ED;Database=Pythondb;Trusted_Connection=yes;' 

SQL Server Authentication

 'DRIVER=;SERVER=DESKTOP-65KMK07\SQLEXPRESS;PORT=1433;DATABASE=Test;UID=sa;PWD=******;' 

pyodbc uses the Microsoft ODBC driver for SQL Server. If your version of the ODBC driver is 17.1 or later, you can use the Azure Active Directory interactive mode of the ODBC driver through pyODBC. This interactive option works if Python and pyODBC permit the ODBC driver to display the dialog. The option is only available on Windows operating systems.

The following example provides an ODBC connection string that specifies Azure Active Directory interactive authentication:

 server=Server;database=Database;UID=UserName;Authentication=ActiveDirectoryInteractive; 

The Microsoft ODBC Driver for SQL Server with version 13.1 or above allows ODBC applications to connect to an instance of Azure SQL Database using a federated identity in Azure Active Directory with a username/password, an Azure Active Directory access token, an Azure Active Directory managed service identity, or Windows Integrated Authentication (Windows driver only).

For the ODBC Driver version 13.1, the Azure Active Directory access token authentication is Windows only. The ODBC Driver version 17 and above support this authentication across all platforms (Windows, Linux, and macOS).

Python Connect to SQL Database

A new Azure Active Directory interactive authentication with Login ID is introduced in ODBC Driver version 17.1 for Windows. A new Azure Active Directory managed service identity authentication method was added in ODBC Driver version 17.3.1.1 for both system-assigned and user-assigned identities.

All of these are accomplished through the use of new DSN and connection string keywords, and connection attributes.

Note that the ODBC Driver on Linux and macOS only supports Azure Active Directory authentication directly against Azure Active Directory. If you are using Azure Active Directory username/password authentication from a Linux or macOS client and your Active Directory configuration requires the client to authenticate against an Active Directory Federation Services endpoint, authentication may fail.

Python Connect to SQL Database

Steps to Connect SQL Server and Fetch data

Syntax of Python Connect to SQL Database

 import pyodbc # Some other example server values are # server = 'localhost\sqlexpress' # for a named instance # server = 'myserver,port' # to specify an alternate port server = 'tcp:myserver.database.windows.net' database = 'mydb' username = 'myusername' password = 'mypassword' cnxn = pyodbc.connect('DRIVER=;SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password) cursor = cnxn.cursor() 

Select Query for Python Database

The cursor.execute function can be used to retrieve a result set from a query against SQL Database. This function accepts a query and returns a result set, which can be iterated over with the use of cursor.fetchone()

 import pyodbc conn = pyodbc.connect('Driver=;' 'Server=DESKTOP-SQQV4ED;' 'Database=Pythondb;' 'Trusted_Connection=yes;') cursor = conn.cursor() cursor.execute('SELECT * FROM dbo.Student') for row in cursor: print(row) 

Python Connect to SQL Database

Insert Query for Python Connect to SQL Database

 cursor.execute(""" INSERT INTO SalesLT.Product (Name, ProductNumber, StandardCost, ListPrice, SellStartDate) VALUES (. )""", 'SQL Server Express New 20', 'SQLEXPRESS New 20', 0, 0, CURRENT_TIMESTAMP) cnxn.commit() row = cursor.fetchone() while row: print('Inserted Product key is ' + str(row[0])) row = cursor.fetchone() 

In above example, you saw how to run an INSERT statement safely, and pass parameters. The parameters protect your application from SQL injection.

Summary

You have seen Python Connect to SQL Database. Once you established such a connection between Python and SQL Server, you can start using SQL in Python to manage your data. I hope you have enjoyed it a lot.

Источник

Шаг 3. Подтверждение концепции, подразумевающее подключение к SQL с помощью pyodbc

Этот пример является подтверждением концепции. Пример кода упрощен для ясности и для него не гарантируется соблюдение рекомендаций корпорации Майкрософт.

Чтобы приступить к работе, выполните следующий пример скрипта. Создайте файл с именем test.py и добавляйте фрагменты кода по ходу работы.

Подключение

import pyodbc # Some other example server values are # server = 'localhost\sqlexpress' # for a named instance # server = 'myserver,port' # to specify an alternate port server = 'tcp:myserver.database.windows.net' database = 'mydb' username = 'myusername' password = 'mypassword' # ENCRYPT defaults to yes starting in ODBC Driver 18. It's good to always specify ENCRYPT=yes on the client side to avoid MITM attacks. cnxn = pyodbc.connect('DRIVER=;SERVER='+server+';DATABASE='+database+';ENCRYPT=yes;UID='+username+';PWD='+ password) cursor = cnxn.cursor() 

Выполнение запроса

Функция cursor.execute может использоваться для извлечения результирующего набора из запроса к базе данных SQL. Эта функция принимает запрос и возвращает результирующий набор, по которому может быть выполнена итерация с использованием cursor.fetchone().

#Sample select query cursor.execute("SELECT @@version;") row = cursor.fetchone() while row: print(row[0]) row = cursor.fetchone() 

Вставка строки

В этом примере вы узнаете, как безопасно выполнить инструкцию INSERT и передать параметры. Параметры защищают приложение от внедрения кода SQL.

#Sample insert query count = cursor.execute(""" INSERT INTO SalesLT.Product (Name, ProductNumber, StandardCost, ListPrice, SellStartDate) VALUES (. )""", 'SQL Server Express New 20', 'SQLEXPRESS New 20', 0, 0, CURRENT_TIMESTAMP).rowcount cnxn.commit() print('Rows inserted: ' + str(count)) 

Azure Active Directory и строка подключения

pyODBC использует драйвер Microsoft ODBC для SQL Server. Если ваша версия драйвера ODBC — 17.1 или более поздняя, интерактивный режим Azure Active Directory драйвера ODBC можно использовать через pyODBC.

Этот интерактивный параметр работает, если Python и pyODBC разрешают драйверу ODBC отображать диалоговое окно. Этот параметр доступен только в ОС Windows.

Пример строки подключения для использования с интерактивной проверкой подлинности Azure Active Directory

В следующем примере представлена строка подключения ODBC, определяющая интерактивную проверку подлинности Azure Active Directory.

См. сведения о параметрах проверки подлинности драйвера ODBC в руководстве по использованию Azure Active Directory с драйвером ODBC.

Дальнейшие действия

Дополнительную информацию можно найти в Центре разработчика Python.

Источник

Step 3: Proof of concept connecting to SQL using pyodbc

This example is a proof of concept. The sample code is simplified for clarity, and doesn’t necessarily represent best practices recommended by Microsoft.

To get started, run the following sample script. Create a file called test.py, and add each code snippet as you go.

Connect

import pyodbc # Some other example server values are # server = 'localhost\sqlexpress' # for a named instance # server = 'myserver,port' # to specify an alternate port server = 'tcp:myserver.database.windows.net' database = 'mydb' username = 'myusername' password = 'mypassword' # ENCRYPT defaults to yes starting in ODBC Driver 18. It's good to always specify ENCRYPT=yes on the client side to avoid MITM attacks. cnxn = pyodbc.connect('DRIVER=;SERVER='+server+';DATABASE='+database+';ENCRYPT=yes;UID='+username+';PWD='+ password) cursor = cnxn.cursor() 

Run query

The cursor.execute function can be used to retrieve a result set from a query against SQL Database. This function accepts a query and returns a result set, which can be iterated over with the use of cursor.fetchone().

#Sample select query cursor.execute("SELECT @@version;") row = cursor.fetchone() while row: print(row[0]) row = cursor.fetchone() 

Insert a row

In this example, you see how to run an INSERT statement safely, and pass parameters. The parameters protect your application from SQL injection.

#Sample insert query count = cursor.execute(""" INSERT INTO SalesLT.Product (Name, ProductNumber, StandardCost, ListPrice, SellStartDate) VALUES (. )""", 'SQL Server Express New 20', 'SQLEXPRESS New 20', 0, 0, CURRENT_TIMESTAMP).rowcount cnxn.commit() print('Rows inserted: ' + str(count)) 

Azure Active Directory and the connection string

pyODBC uses the Microsoft ODBC driver for SQL Server. If your version of the ODBC driver is 17.1 or later, you can use the Azure Active Directory interactive mode of the ODBC driver through pyODBC.

This interactive option works if Python and pyODBC permit the ODBC driver to display the dialog. The option is only available on Windows operating systems.

Example connection string for Azure Active Directory interactive authentication

The following example provides an ODBC connection string that specifies Azure Active Directory interactive authentication:

For more information about the authentication options of the ODBC driver, see Using Azure Active Directory with the ODBC Driver.

Next steps

For more information, see the Python Developer Center.

Источник

Оцените статью