Skip to main content Skip to footer

Connecting Python to MS SQL Using PyODBC

From your DIFM Windows Server Virtual Machine

How to Connect Python Script to DIFM Database:

 

  1. Download & Install VS Code – (or any python development editor of your choice.)
  2. Install Python Version 3.11,

         Choose Custom Installation

         Click on Advanced

          Check - Modify Path and Environmental Variables

  1. Install Python Extensions in VS Code

 

  1. INSTALL PIP:

 

          Using a Command Prompt:

                   py -m pip install --upgrade pip

 

  1. pip install pandas

          pip install pyodbc

                  If Error:  You must install C ++ Build Tools

                  https://visualstudio.microsoft.com/visual-cpp-build-tools/

 

  1. Create your Python File

 In this case we will use SQL to view all products that are seeds in the products table..   The pyODBC connection string is below

_____________________________________________________

import pandas as pd
import pyodbc

conn = pyodbc.connect('DRIVER={SQL Server};SERVER=132.145.129.240;PORT=1433;DATABASE=difm_clone;UID=dev;PWD=YourPassword;')


df = pd.read_sql_query("""SELECT ProductName, Type FROM products WHERE type='seed' ORDER BY ProductName ASC""", conn)

print(df)
print(type(df))

Developer Note:

Wrap Your SQL in Quotes!

Python does not care if you use single or double quotes, but SQL does. And when you use SQL within Python you need to wrap your query in quotes. 

In Python, wrap your SQL string in three double quotes.

Use double quotes for any table or field in the database.

Use single quotes for any data you want to select/insert/update in the database.

This way, Python and SQL are happy.

March 07, 2023

Integration with Oracle IDCS Complete!

The DIFM Ag Research Portal and Farmers Portal is now integrated with Oracle IDCS and there is self-registration for farmers and research scientists.   Both applications remain under development but the underlying scaffolding is built and being tested.

Ag Research Portal:  Is an end-user application under development designed for PI's and Stakeholders to access, review, edit migrated data residing in DIFM's Autonomous Data Warehouse in the Oracle Cloud.  

Farm Portal: Is an end-user application allowing farmers to register for OFPE Trials, upload necessary data for implementing those trials.  

Integrating user registration with IDCS and managing application & data access with IDCS satisfies essential requirements of Phase I of the software development plan.