![](/img/trans.png)
[英]System.InvalidCastException: 'Specified cast is not valid.' C# MYSQL
[英]System.InvalidCastException: Specified cast is not valid in C# using postgres datareader
我试图在C#中使用postgre从数据库中提取数据,并将返回的值放在标签控件中。 我一直在获取System.InvalidCasaeExeception。 数据库字段是整数,因此我使用数据读取器来获取值。
这是我的代码
private void Get_Defects()
{
NpgsqlConnection conn = Connection.getConnection();
try
{
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("select * from defect where defect_id >= :MinID and defect_id <= :MaxID and location_id = 102 and top_or_bottom = :TopBottom;", conn);
cmd.Parameters.Add(new NpgsqlParameter("MinID", MinID));
cmd.Parameters.Add(new NpgsqlParameter("MaxID", MaxID));
cmd.Parameters.Add(new NpgsqlParameter("TopBottom", TopBottom));
NpgsqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
lblCrookedPart.Text = dr.GetInt32(12).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close();
}
}
}
不知道为什么它不起作用。 我拉了第一个元素,它显示正确。 一些数据是整数,但数据库中的值为空。 我尝试了带有数据的元素,但出现强制转换异常错误。 请帮忙。
我成功了,谢谢大家的帮助和提示!!
这是工作代码的摘要
conn.Open();
NpgsqlDataAdapter da = new NpgsqlDataAdapter("select * from defect where defect_id >= '"+MinID+"' and defect_id <= '"+MaxID+"' and location_id = 102 and top_or_bottom = '"+TopBottom+"';", conn);
ds.Reset();
da.Fill(ds);
dt = ds.Tables[0];
//Used to sum the column values
object CrookedPartTotal = dt.Compute("Sum(crooked_part)", "defect_id >= '" + MinID + "' and defect_id <= '" + MaxID + "'");
if (CrookedPartTotal.ToString() == "")
lblCrookedPart.Text = "0";
else
lblCrookedPart.Text = CrookedPartTotal.ToString();
object TooMuchSolder = dt.Compute("Sum(too_much_solder)", "defect_id >= '" + MinID + "' and defect_id <= '" + MaxID + "'");
if (TooMuchSolder.ToString() == "")
lblTooMuchSolder.Text = "0";
else
lblTooMuchSolder.Text = TooMuchSolder.ToString();
您应该检查该值是否不为null。 请尝试以下操作:
lblCrookedPart.Text = (dr.IsDBNull(12)) ? "NULL" : dr.GetInt32(12).ToString();
试试这个
NpgsqlDataReader da = default(NpgsqlDataReader);
NpgsqlCommand cmd = new NpgsqlCommand("select * from myTable", GenConnection);
string strVAL = null;
da = cmd.ExecuteReader;
if (da.HasRows) {
while (da.Read) {
strVAL = (Information.IsDBNull(da["field"]) ? 0 : da["field"]).ToString;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.