Quantcast
Channel: Silk Test Knowledge Base
Viewing all articles
Browse latest Browse all 105

How to query a Database and write results to text file using a .net script?

$
0
0
Current Revision posted to Silk Test Knowledge Base by Mark H on 2/7/2019 2:43:59 PM

You can use the System.Data.SqlClient reference to make a connection to the database (using SqlConnection), execute the SQL statement (using SqlCommand) and print the results to a text file (using SqlDataReader).

Please see example below that executes a SQL statement on a SQL Server database and writes the results to a text file (C:\MyQuery.txt) using a Silk Test Workbench .net script:-

Imports System.Data.SqlClient
Imports System.Data
Imports System.IO

Public Module Main
    
    Dim myConnectDB As System.Data.SqlClient.SqlConnection
    Dim myConnectStr As String
    Dim mySQLCommand As System.Data.SqlClient.SqlCommand
    Dim myReader As System.Data.SqlClient.SqlDataReader

    Public Sub Main()
        
        'Connection to my SQL Server database
        myConnectStr = "Server=<HOSTNAME\INSTANCE>;Database=<DBNAME>;User Id=<USER>;Password=<PASSWORD>;"
        myConnectDB = New System.Data.SqlClient.SqlConnection(myConnectStr)
        
        myConnectDB.Open()
        ' SQL Select statement to read data from the desired table
        mySQLCommand = New System.Data.SqlClient.SqlCommand("Select * FROM STW_USERS;",myConnectDB) 
     
        Dim myReader As SqlDataReader = mySQLCommand.ExecuteReader()
        Dim fileName As String = "C:\MyQuery.txt"
        'create a stream object which can write text to a file
        Dim outputStream As StreamWriter = New StreamWriter(fileName)

      Do While myReader.Read
        Dim values(myReader.FieldCount - 1) As Object
        'get all the field values
        myReader.GetValues(values)

       'write the text of each value to a comma seperated string
        Dim line As String = String.Join(",", values)
        outputStream.WriteLine(line)
      Loop
      myReader.Close()
      outputStream.Close()

      myConnectDB.Close()
    
    End Sub
End Module

Tags: query sql write server database sqlclient system sqlcommand sqldatareader sqlconnection outputstream

Viewing all articles
Browse latest Browse all 105

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>