-1

使用此代码,我在与参数 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;
        }
    }
4

1 回答 1

0

首先,请使用您的调试器并检查id发生异常的值,这可能有助于发现问题。

此外,检查表“类别”中“idcategory”id列的类型和数据类型。也许这些数据类型之间存在差异,从而导致异常。

也可能是,'idcategory'不会自动插入,因此您必须将其包含在您的INSERT语句中。('SELECT LASTVAL()'返回null吗?)

除此之外,我总是更long idCategory = Convert.ToInt64(id)喜欢long idCategory = (long)id.

如果要避免异常,请使用long idCategory = id as long并检查是否idCategory == null

于 2013-02-15T14:19:36.617 回答