Tuesday, March 13, 2007

GetOrdinal example


When you use the ExecuteReader,
you have to select the fields created from the select statement.

There you have to be carefull with the numbers you give in the reader.

Here is the example using a MySQL database:

String select = "Select id, first_name, last_name, nickname from table_name"
MySqlCommand command
= new MySqlCommand();
MySqlDataReader reader;
MakeConnection();
command.Connection
= connect;
command.CommandText
= select;
reader
= command.ExecuteReader();
while (reader.Read())
{
//-> Fist column selected
int id = reader.GetInt32(0);
//->Second Column Selected
string FirstName = reader.GetString(1) ;
//->3é Column Selected
string LastName = reader.GetString(2) ;
//->Last Column Selected
string NickName = reader.GetString(3) ;
}
MakeDisconnection();


But when you change the select statement you have to pay attention that the order is exact the same order for the reader.

By Using the GetOrdinal is the possiton not a problem anymore.

This example show's the use of GetOrdinal:
(Only the select statement is changed by order.)


 

String select = "Select nickname, last_name, first_name, id from table_name"
MySqlCommand command
= new MySqlCommand();
MySqlDataReader reader;
MakeConnection();
command.Connection
= connect;
command.CommandText
= select;
reader
= command.ExecuteReader();
while (reader.Read())
{
//-> Fist column selected
int id = rdr.GetInt32(rdr.GetOrdinal("id"));
//->Second Column Selected
string FirstName = reader.GetString(rdr.GetOrdinal("first_name")) ;
//->3é Column Selected
string LastName = reader.GetString(rdr.GetOrdinal("last_name")) ;
//->Last Column Selected
string NickName = reader.GetString(rdr.GetOrdinal("nickname")) ;
}
MakeDisconnection();

This works and you don't have any troubles with the order.

1 comment:

Anonymous said...

Great work.