我希望在数据库中搜索,如果代码存在,则设置ID等于会话[SID]。我的表的ID是uniqueidentifier
,它有错误。错误发生在r.read();
:
从字符串转换为uniqueidentifier时转换失败
码:
protected void btnSearch_Click(object sender, EventArgs e)
{
string CodeReg = txtCodeReg.Text;
Guid g = new Guid();
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.;Initial Catalog=Db_Hospital;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Select CodeMeli From Tbl_Staff where (ID=@ID)";
cmd.Parameters.AddWithValue("@ID", txtCode.Text);
SqlDataReader r = cmd.ExecuteReader();
r.Read();
if (r.HasRows)
{
Session["SID"] = g;
}
}
AddWithValue将创建一个参数,其类型是传递的值的类型。在您的情况下,此参数的类型为string。但要正常工作,您应该传递一个uniqueidentifier。
if (!Guid.TryParse(txtCode.Text, out Guid result))
{
Console.WriteLine("not a valid guid");
return;
}
cmd.Parameters.Add("@id", SqlDbType.UniqueIdentifier).Value = result;
通常,您应该尝试避免使用此AddWithValue,因为有许多不可容忍的副作用。你可以在这里阅读这个场景
另一种可能的解决只需将ID uniqueidentifier转换为VARCHAR(36)即可。
protected void btnSearch_Click(object sender, EventArgs e)
{
string CodeReg = txtCodeReg.Text;
Guid g = new Guid();
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.;Initial Catalog=Db_Hospital;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Select CodeMeli From Tbl_Staff where (CONVERT(VARCHAR(36),ID)=@ID)";
cmd.Parameters.AddWithValue("@ID", txtCode.Text);
SqlDataReader r = cmd.ExecuteReader();
r.Read();
if (r.HasRows)
{
Session["SID"] = g;
}
}