Ejecutar una consulta parametrizada

2042 vistas

Es posible pasar parámetros a las consultas SQL.

Veamos un ejemplo con SQL Server



vbnet
  1. using System.Data.SqlClient;
  2. Imports System.Data.SqlClient
  3.  
  4. ' cadena de conexión
  5. Dim connectString As String = "database=equities;server=JV01;User ID=samfisher;pwd=echelon"
  6. ' Objeto connection
  7. Dim connection As SqlConnection = New SqlConnection(connectString)
  8. ' obertura
  9. connection.Open()
  10. ' Objeto Command
  11. Dim command As SqlCommand = New SqlCommand("SELECT * FROM usr_contract WHERE " + _
  12.                                           "ctr_ref = @contract AND ctr_exg_ref = @exg", _
  13.                                           connection)
  14. ' parámetros
  15. command.Parameters.Add(New SqlParameter("@contract", SqlDbType.VarChar, 5))
  16. command.Parameters("@contract").Value = "FTE"
  17. command.Parameters.Add(New SqlParameter("@exg", SqlDbType.VarChar, 8))
  18. command.Parameters("@exg").Value = "SBF"
  19. ' Objecto datareader
  20. Dim reader As SqlDataReader = command.ExecuteReader()
  21. Dim row As Object()
  22. While reader.Read()
  23.  
  24.     If row Is Nothing Then
  25.         row = New Object(reader.FieldCount - 1) {}
  26.     End If
  27.     reader.GetValues(row)
  28.     For i As Integer = 0 To row.GetLength(0) - 1
  29.         If Not row(i) Is DBNull.Value Then
  30.             Console.Write(row(i))
  31.         Else
  32.             Console.Write("NULL")
  33.         End If
  34.         If i < row.GetUpperBound(0) Then
  35.             Console.Write(" | ")
  36.         End If
  37.     Next
  38.     Console.WriteLine()
  39. End While
  40.  
  41. ' Cierre reader
  42. reader.Close()
  43. ' Cierre connection
  44. connection.Close()