【问题标题】:read a table with uniqueidentifier ID读取具有唯一标识符 ID 的表
【发布时间】:2018-09-03 18:48:36
【问题描述】:

我想在数据库中搜索,如果代码存在,则设置 ID 等于 session[SID]。 我的表的 ID 是 uniqueidentifier 并且它有错误。错误在r.read();:

从字符串转换为唯一标识符时转换失败

代码:

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;
    }
}

【问题讨论】:

    标签: c# asp.net session webforms uniqueidentifier


    【解决方案1】:

    AddWithValue 将创建一个参数,其类型是传递的值的类型。在您的情况下,此参数是字符串类型。但要正常工作,您应该传递一个唯一标识符。

    if (!Guid.TryParse(txtCode.Text, out Guid result))
    {
        Console.WriteLine("not a valid guid");
        return;
    }
    cmd.Parameters.Add("@id", SqlDbType.UniqueIdentifier).Value = result;
    

    一般而言,您应该尽量避免使用此 AddWithValue,因为它会产生许多不希望的副作用。您可以在

    中阅读有关此场景的信息

    Using Parameters.AddWithValue in SqlDataAdapter

    【讨论】:

      【解决方案2】:

      另一个可能的解决方案。只需将 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;
          }
      }
      

      【讨论】:

      • 不确定,但可能这会使 ID 字段(如果有)上的索引不可用
      猜你喜欢
      • 1970-01-01
      • 2018-03-01
      • 2012-07-03
      • 1970-01-01
      • 2021-05-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      相关资源
      最近更新 更多