Scripting: How to access a database

0 Likes

Below example shows how you can read data from a MS SQL database and store it in the response. For simplicity and easy reproduction, I'm using the same database as a Service Virtualization itself. If you would like to use a different database vendor, just add a relevant database driver dll and amend the code accordingly.

using System.Data.SqlClient;  
using HP.SV.CSharp;  
  
namespace HP.SV {  
  public class CSharpRule {  
    public static void Execute(HpsvRootObject sv) {  

      using (SqlConnection conn = new SqlConnection()) {  
        conn.ConnectionString = "Server=127.0.0.1\\SQLEXPRESS_SV;Database=YOUR_DB_NAME;Trusted_Connection=true";  
        conn.Open();  
  
        SqlCommand command = new SqlCommand("SELECT ID, NAME, DESCRIPTION FROM VS", conn);  
  
        using (SqlDataReader reader = command.ExecuteReader()) {  
          // while there is another record present  
          while (reader.Read()) {  
            string id = reader[0].ToString();  
            string name = reader.GetString(1);  
            string description = reader.GetString(2);  
  
            sv.Response.getMemberDetailResponse.getMemberDetailResult.person.name.firstName = name;  
            break;  
          }  
        }  
      }  
    }  
  }  
}

Labels:

How To-Best Practice
Comment List
Anonymous
Related Discussions
Recommended