How popular list of objects with result of select (C # and MySQL)?

0
string strSQL = "SELECT usuperm.idusuario, usuperm.codfunc, usuperm.perm FROM usuperm INNER JOIN usuarios ON usuarios.idusuario = usuperm.idusuario WHERE usuarios.loginusuario = @loginusuario AND usuarios.senhausuario = @senhausuario";
MySqlCommand cmdSQL = new MySqlCommand(strSQL, Conexao.Abrir());
cmdSQL.Parameters.AddWithValue("loginusuario", loginusuario);
cmdSQL.Parameters.AddWithValue("senhausuario", senhausuario);


MySqlDataReader drPerm = cmdSQL.ExecuteReader();
List<PropPerm> listPermn;


//... daqui não sei se uso foreach while ou if
    
asked by anonymous 04.03.2017 / 02:18

2 answers

0

You can do with while :

string strSQL = "SELECT usuperm.idusuario, usuperm.codfunc, usuperm.perm FROM usuperm INNER JOIN usuarios ON usuarios.idusuario = usuperm.idusuario WHERE   usuarios.loginusuario = @loginusuario AND usuarios.senhausuario =    @senhausuario";
MySqlCommand cmdSQL = new MySqlCommand(strSQL, Conexao.Abrir());
cmdSQL.Parameters.AddWithValue("loginusuario", loginusuario);
cmdSQL.Parameters.AddWithValue("senhausuario", senhausuario);

MySqlDataReader drPerm = cmdSQL.ExecuteReader();
List<PropPerm> listPermn = new List<PropPerm>();
while(drPerm.Read())
{
    PropPerm pp = new PropPerm() {
        //suas propriedades. Ex:
        Id = Convert.ToInt32(drPerm["id"]);
    };
    listPermn.Add(pp);
}
drPerm.Close();
cmdSQL.Close();

See also

I recommend you take a look at block using . It ensures that features such as connection, command, and reader will always be closed.

Here has a DevMedia post about it.

    
04.03.2017 / 16:01
0

Thanks, Igor, but I could not do it the same way you showed it, I've been thinking better and decided that it would be better to use a DataTable, I did the following and it's working:

string strSQL = "SELECT usuperm.idusuario, usuperm.codfunc, usuperm.perm FROM usuperm INNER JOIN usuarios ON usuarios.idusuario = usuperm.idusuario WHERE usuarios.loginusuario = @loginusuario AND usuarios.senhausuario = @senhausuario";
MySqlCommand cmdSQL = new MySqlCommand(strSQL, Conexao.Abrir());
cmdSQL.Parameters.AddWithValue("loginusuario", loginusuario);
cmdSQL.Parameters.AddWithValue("senhausuario", senhausuario);
MySqlDataReader drPerm = cmdSQL.ExecuteReader();

DataTable perm = new DataTable();

if (drPerm.HasRows == true)
{
    perm.Load(drPerm);

    return perm;
}
else
{
    return perm;
}
    
16.03.2017 / 04:22