I am working with vb.net and in the class conexion
I have the following method:
Function consulta()
Try
conectar()
comando = conexion.CreateCommand()
comando.CommandText = "select * from persona"
reader = comando.ExecuteReader()
Catch ex As Exception
MsgBox("Error 1 " + ex.ToString)
End Try
desconectar()
Return reader
End Function
The object reader
is of type SqlDataReader
.
What I need is not to enter the results in a DataGrid
, but to call them from the form and display each field in a TextBox
. For example the field nombre
enter it in a TextBox
, the apellido
in another TextBox
.
There are 2 very serious and fundamental problems in the current design you have that the other answers haven't mentioned:
SqlDataReader
.desconectar()
) before returning theSqlDataReader
, so when you try to read the data with theSqlDataReader
, it's going to throw you exceptions.Time after time I am seeing questions where this pattern of using global connections is being used. This is very bad practice and will cause problems in more serious programs. There is nothing wrong with centralizing the code that opens the connection. But it is not correct to save the connection in a global variable.
And the problem with the second point is that in order to return a
SqlDataReader
and be able to continue using it, the connection must be left open. But if you remove the calldesconectar()
from your method to fix this problem, your code now becomes even more brittle than it already is, because it's not very clear who has responsibility for closing the connection.Here is a much more solid and reusable pattern that you can use to read the data from a
SqlDataReader
for any query and that does not fall into the design problems mentioned above.For the example that I share with you, I am going to assume that instead of having a method
conectar()
that opens a connection and assigns it to a global variable (to avoid), I am going to assume that you have defined a methodCrearConexion
that simply returns a new instance ofSqlConnection
without assigning it to a global variable (correct). Something like:Method
EjecutarLeerConsulta
:With this method, you can execute and read any query using best practices, without global variables, without having to worry about when to open and close the connection, etc. Everything is handled automatically in this central method.
How to use it
To use the method, you need to pass at least 2 parameters to it:
SqlParameter
) if the query requires them.Example:
And if you need to build queries with parameters, the call would look like this:
Well, first I recommend that you add the type that you are going to return to the method at the end. Thus:
now to get the data from the data reader you do it this way
It uses the SQLDataReader class, in c# you can call it by index or by column name as follows