Sitemap
Roshberry Digital

Sharing Ideas, Concepts and Thoughts

Connecting to SQL Server using IronPython

2 min readMay 29, 2020

--

Press enter or click to view image in full size

IronPython is an open-source implementation of Python programming language which is tightly integrated with the .NET Framework. IronPython can use the .NET Framework and Python libraries like wise other.NET languages can use Python script without a hassle.

Firstly, you have to set up environment for IronPython and SQL Server.

You check my below posts to set up the environment.

Connecting to SQL Server using Python

IronPython Set up

You can download and install IronPython from this link

Get Velammal Ayyappan’s stories in your inbox

Join Medium for free to get updates from this writer.

Create a test database which has a sample table with some data stored.

Sample IronPython script to fetch data from SQL Server

In Visual Studio, Create a new IronPython application and write a below sample script and execute it.

Press enter or click to view image in full size

import clr
clr.AddReference(‘System.Data’)
from System.Data import *

#Connection string
conn = SqlClient.SqlConnection(‘server=yourserver;database=testdatbase;uid=userid;password=password’)
conn.Open()

cmd = SqlClient.SqlCommand(‘select * from customers’, conn)
reader = cmd.ExecuteReader()

if reader.HasRows:
while reader.Read():
customer = {
‘id’: reader.GetString(reader.GetOrdinal(“customer_id”)),
‘name’: reader.GetString(reader.GetOrdinal(“customer_name”)),
‘city’:reader.GetString(reader.GetOrdinal(“city”))
}
customers.append(customer)

conn.Close()
print(‘ — — — — Id — — — — — Name — — — — — City — — — — ‘)
for customer in customers:
print(‘ %d %s %s ‘ %(customer.id,customer.name,customer.city))
print(‘ — — — — — — — — — — — — — — — — — — — — — — — -’)

Output

To run the application:

  1. From Solution Explorer → select the python file you want to execute.
  2. Right-click and select Start without Debugging option.

You can see the output in a specified format in command prompt window.

--

--

Velammal Ayyappan

Written by Velammal Ayyappan

Android Developer | Interested in Mobile Technologies and Hybrid Programming.