我使用此代码从SQL Server获取数据:
string rootname = "[" + nameroot + "]";
string retVal = "";
string constring = "Data Source =(Local);Initial Catalog=Tajari;Integrated Security=True;";
SqlConnection conobj = new SqlConnection(constring);
string commandtext = "select distinct " + rootname + " from TBLJobsRootName where MenuId between 1 and " + countroot + "";
SqlCommand comobj = new SqlCommand(commandtext, conobj);
conobj.Open();
SqlDataReader dr = comobj.ExecuteReader();
while (dr.Read())
{
//retVal = dr[nameroot].ToString();
}
conobj.Close();
现在我需要将这些数据插入到变量或文本框中。
问题是我的价值未知
答案 0 :(得分:2)
解决方案1:
您可以使用Index
值。
试试这个:
while (dr.Read())
{
retVal = dr[0].ToString();
}
解决方案2:
您也可以使用别名。
string commandtext = "select distinct " + rootname + " as myrootname from
TBLJobsRootName where MenuId between 1 and " + countroot + "";
SqlCommand comobj = new SqlCommand(commandtext, conobj);
conobj.Open();
SqlDataReader dr = comobj.ExecuteReader();
while (dr.Read())
{
retVal = dr["myrootname"].ToString();
}
建议:您的查询对 SQL注入攻击开放我建议您使用参数化查询来避免它们。
解决方案3:使用参数化查询
如果要添加所有根名称值,则需要将所有值添加到List。
List<string> list = new List<string>();
string commandtext = "select distinct "+rootname+" as myrootname from
TBLJobsRootName where MenuId between 1 and @countroot";
SqlCommand comobj = new SqlCommand(commandtext, conobj);
comobj.Parameters.AddWithValue("@countroot",countroot);
conobj.Open();
SqlDataReader dr = comobj.ExecuteReader();
while (dr.Read())
{
lis.Add(dr["myrootname"].ToString());
}
//You can retunrn list