我有以下代码:
SqlConnection c = new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=BookStoreDataBase1;Integrated Security=True;Pooling=False;"); c.Open(); string raf = string.Format("Select Id from Customer WHERE email='{0}'", DropDownList1.SelectedItem.Text); SqlCommand comm2 = new SqlCommand(raf, c); SqlDataReader r = comm2.ExecuteReader();
该对象r现在具有查询的值,该行包含该ID,其中电子邮件等于下拉列表中的随机值。
r
我想要的是获取该“ Id”的确切值并将其分配给label。请帮我。
首先,您的查询是开放的,SQL Injection attack因此需要进行如下更改:-
SQL Injection attack
string raf = "Select Id from Customer WHERE email= @Email"; SqlCommand comm2 = new SqlCommand(raf, c); cmoo2.Parameters.Add("@Email",SqlDbType.NVarchar,20).Value = DropDownList1.SelectedItem.Text;
您只获取一个值,因此可以ExecuteScalar像这样使用它:-
ExecuteScalar
labelid.Text= cmoo2.ExecuteScalar.ToString();
但是,如果要使用SqlDataReader对象,则在调用该Read方法时它将返回值:
SqlDataReader
Read
using(SqlDataReader reader= cmoo2.ExecuteReader()) { while (reader.Read()) { labelid.Text= reader["Id"].ToString(); } }