[英]How can I search in a column of a datatable in SQL?
這是代碼:
// 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();
我不能得到所有的列,像這樣我只得到列的名稱,所以會出現問題。
我收到此錯誤:
System.Data.SqlClient.SqlException :'冒號無效:'idgroupe'
注意: idgroupe
是 DataTable 中列的名稱
錯誤是命令
cmd = new SqlCommand("select nom from groupe where ID IN("+dt.Columns[0]+")", cn);
此文本翻譯為“從 ID IN(idgroupe) 的 groupe 中選擇 nom”意思是正在搜索表組上的列 nom,其中 Id 在列 idgroupe 中,這可能不存在。
我們不知道您真正想要什么,但至少應該在括號周圍加上簡單的引號,類似於您在第一個命令中所做的。
無論如何,您應該閱讀有關 Sql 注射( https://www.troyhunt.com/stored-procedures-and-orms-wont-save/ )
並將您的命令更改為類似
using(cmd = new SqlCommand("select idgroupe from enseigner where idformateur = @id", cn))
{
cmd.Parameters.AddWithValue("@id", Session["matricule"]);
(...)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.