Search code examples
silverlightironpython-studio

Can we acess SQL Server data from Iron Python Script File if so how I m trying this following code?


Can we access SQL Server data from Iron Python script file if so how I m trying this following code ?

import sys

import clr
clr.AddReference("System.Windows")
from System.Windows import Application

import pypyodbc
constr="DRIVER={SQL Server Native Client 10.0};Data Source=SERVERName;Initial Catalog=DBName;Integrated Security=True"
cnxn=pypyodbc.connect(constr)

da=cnxn.cursor("Select Ename from tbl_Empployee where Emp_id=1",cn)
da.execute();

for row in da.fetchall():
    for field in row: 
        Application.Current.RootVisual.FindName("textBox2").Text = field

Solution

  • You can use the .net native types, see: What's the simplest way to access mssql with python or ironpython?

    your code could look like this:

    import clr
    clr.AddReference('System.Data')
    from System.Data.SqlClient import SqlConnection, SqlParameter
    
    conn_string = 'data source=SRG3SERVER; initial catalog=vijaykumarDB; trusted_connection=True'
    connection = SqlConnection(conn_string)
    connection.Open()
    command = connection.CreateCommand()
    command.CommandText = 'Select Ename from tbl_Empployee where Emp_id=@employeeId'
    command.Parameters.Add(SqlParameter('@employeeId', 1))
    
    reader = command.ExecuteReader()
    while reader.Read():
        print reader['Ename']
    
    connection.Close()