需要在c#中使用字符串从数据库中查找ID号
本文关键字:数据库 查找 ID 字符串 | 更新日期: 2023-09-27 18:02:18
我需要从标签中获取数据,我已经从上一页使用该标签的会话中获得数据,我需要使用它来查找该数据的ID,例如,如果标签包含单词' 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();
}
}
改变这一行
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注入攻击。您应该使用SqlParameter
而不是连接查询。
更多阅读,你可以使用这个链接:http://www.w3schools.com/sql/sql_injection.asp
就像缺少sql的引号一样简单。
sql-> where D_Name = 'somevalue'
…所以你的代码应该是
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 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 + "%'";