我认为我的查询是正确的,但无法正常工作,并抛出以下异常:
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();
答案 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
}
}
}
这种方法从三个方面改进了代码。