使用此代码,我在与参数 categoryName 对应的表中搜索 id。如果不存在,我在表中插入值,然后返回键。当被执行long idCategory = (long) id;
时,有时它会起作用,有时会抛出无效的强制转换异常。为什么???
public static long GetCategoryID(String categoryName)
{
using (NpgsqlConnection conn = new NpgsqlConnection(ConfigurationManager.ConnectionStrings["myConn"].ToString()))
{
conn.Open();
NpgsqlTransaction transaction = conn.BeginTransaction();
String query = "SELECT idcategory FROM category WHERE categoryname = '" + categoryName + "';";
NpgsqlCommand cmd = new NpgsqlCommand(query, conn, transaction);
object id = cmd.ExecuteScalar();
if (id == null)
{
query = "INSERT INTO Category (categoryname) VALUES ('" + categoryName +"');";
cmd = new NpgsqlCommand(query, conn, transaction);
cmd.ExecuteNonQuery();
query = "SELECT LASTVAL();";
cmd = new NpgsqlCommand(query, conn, transaction);
id = cmd.ExecuteScalar();
}
long idCategory = (long)id;
transaction.Commit();
conn.Close();
return idCategory;
}
}