Npgsql.PostgresException:'外部组件引发了异常

时间:2019-05-18 12:31:00

标签: asp.net postgresql

我认为我的查询是正确的,但无法正常工作,并抛出以下异常:

  

Npgsql.PostgresException:'外部组件引发了异常。

private async void Load_Click(object sender, RoutedEventArgs e)
{

    NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1; Port=5432; User Id=postgres; Password=hadilala; Database=HCM");
    conn.Open();
    string str = "select Hrcode,FirstNameEng,FirstName from rec.Person where Hrcode='" + uxHrCode.Text + "'";
    NpgsqlCommand comm1 = new NpgsqlCommand(str, conn);

    NpgsqlDataReader DR1 = comm1.ExecuteReader();
    if (DR1.Read())
    {

        DR1.GetValue(1).ToString();
        DR1.GetValue(2).ToString();

    }
    CardModel card = new CardModel()
    {
        HrCode = uxHrCode.Text,
        Name = DR1.GetValue(1).ToString(),
        NameLocal = DR1.GetValue(2).ToString(),
    };


    uxHrCode.Text = "";

    conn.Close();

1 个答案:

答案 0 :(得分:0)

对代码的某些改进可能会解决问题

private async void Load_Click(object sender, RoutedEventArgs e)
{

    string str = @"select Hrcode,FirstNameEng,FirstName 
                   from rec.Person where Hrcode=:code";
    using(NpgsqlConnection conn = new NpgsqlConnection("....."))
    using(NpgsqlCommand comm1 = new NpgsqlCommand(str, conn))
    {
        conn.Open();
        comm1.Parameters.AddWithValue(":code", NpgssqlDbType.Text).Value = uxHrCode.Text;
        using(NpgsqlDataReader DR1 = comm1.ExecuteReader())
        {
            if (DR1.Read())
            {
                 CardModel card = new CardModel()
                 {
                     HrCode = uxHrCode.Text,
                     Name = DR1.GetValue(1).ToString(),
                     NameLocal = DR1.GetValue(2).ToString(),
                 };
                 uxHrCode.Text = "";
            }
            else
            // Provide message to inform your user that 
            // no match has been found for the HrCode value
        }
    }
}

这种方法从三个方面改进了代码。

  1. 使用声明可确保关闭一次性物品并 避免资源泄漏并减轻服务器负担
  2. 使用用户输入创建查询时,参数是必需的。 没有它们,您可能会在字符串,小数点解析问题 和日期,但最重要的是避免Sql Injection
  3. 如果没有与传递的代码匹配的记录,则不要尝试 使用DataReader。