简体   繁体   中英

How can I search in a column of a datatable in SQL?

This is the code:

// get id groupe
cmd = new SqlCommand("select idgroupe from enseigner where idformateur = '"+Session["matricule"]+"'", cn);

dr = cmd.ExecuteReader();
dt.Load(dr);
dr.Close();

// get group name
cmd = new SqlCommand("select nom from groupe where ID IN("+dt.Columns[0]+")", cn);

dr = cmd.ExecuteReader();

// fill dropdown list 
while (dr.Read())
{
    DropDownList1.Items.Add(dr[0].ToString());
}

dr.Close();
cn.Close();

I can't get all columns, like this I get just the name of columns, so that make problem.

I get this error:

System.Data.SqlClient.SqlException : 'Nom de colonne non valide : 'idgroupe'

NB: idgroupe is the name of column in DataTable

The error is the command

cmd = new SqlCommand("select nom from groupe where ID IN("+dt.Columns[0]+")", cn);

This text translates to "select nom from groupe where ID IN(idgroupe)" Meaning that is searching the column nom on table group where Id is in column idgroupe, that probably does not exist.

We don't know what you actually want, but there should at least be simple quotes around the parentheses, similar to what you did on the first command.

Anyway, you should read about Sql Injection ( https://www.troyhunt.com/stored-procedures-and-orms-wont-save/ )

And change your commands to something like

using(cmd = new SqlCommand("select idgroupe from enseigner where idformateur = @id", cn))
{
 cmd.Parameters.AddWithValue("@id", Session["matricule"]);
  (...)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM