我需要使用该标签中的Sessions从上一页返回的标签中获取数据我需要使用它来查找该数据的ID,例如,如果Label包含word' IT'它需要在数据库中找到它的ID D_ID = 5代码在下面给出
public partial class FinalFeedback1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetDataFromSession();
GetDID();
AddDynamicLabels();
}
public void GetDID()
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataReader myReader1 = null;
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
SqlCommand cmd1 = new SqlCommand(depart, connection);
myReader1 = cmd1.ExecuteReader(); // i am getting error here "Invalid column name 'IT'"
while (myReader1.Read())
{
Label9.Text = myReader1["D_ID"].ToString();
}
}
}
public void AddDynamicLabels()
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataReader myReader2 = null;
string CmdString = "Select Q_ID,Question_Data FROM QuestionTable where D_ID=" + Label9.Text + "";
SqlCommand cmd = new SqlCommand(CmdString, connection);
myReader2 = cmd.ExecuteReader();
while (myReader2.Read())
{
QID1.Text = myReader2["Q_ID"].ToString();
if (QID1.Text == ("1"))
{
Question1.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text ==("2"))
{
Question2.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("3"))
{
Question3.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("4"))
{
Question4.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("5"))
{
Question5.Text = myReader2["Question_Data"].ToString();
}
}
}
}
private void GetDataFromSession()
{
Label2.Text = Session["SNL"].ToString();
Label4.Text = Session["SNB"].ToString();
Label6.Text = Session["EMPID"].ToString();
Label8.Text = Session["DNAME"].ToString();
}
}
答案 0 :(得分:1)
更改此行。
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
到这一行
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
请参阅第二行中的单引号。您的string
值不是单引号,这就是原因。
编辑:您的代码对SQL Injection Attack开放。您应该使用SqlParameter
而不是连接查询。
如需更多阅读,您可以使用以下链接: http://www.w3schools.com/sql/sql_injection.asp
答案 1 :(得分:0)
就像错过了sql的引文一样简单。
SQL-> "其中D_Name =' somevalue'
...因此,您的代码的修复将是
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
答案 2 :(得分:0)
更改此行。
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
到
string depart = "select D_ID from Department where D_Name like '" + Label8.Text + "'";
或更快的搜索
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
或搜索类似字符串更改为
string depart = "select D_ID from Department where D_Name like '%" + Label8.Text + "%'";