2

I have a table.this is the script for my table:-

CREATE TABLE news
(
  news_id bigint NOT NULL DEFAULT nextval('news_seq'::regclass),
  title character varying(1024),
  description character varying(2024),
  CONSTRAINT pk_news_newsid PRIMARY KEY (news_id)  
)
WITH (
  OIDS=FALSE
);
ALTER TABLE news OWNER TO viewer;

Now I want to get the auto generated news_id on insert the new record in the table.

This is C# function for insert the news:-

 public Int64 AddNews(News newNews)
    {
        string query = string.Empty;
        try
        {
            string dateFormat = ConfigurationManager.AppSettings["DateFormat"];
            NpgsqlParameter[] parm = new NpgsqlParameter[2];
            parm[0] = new NpgsqlParameter("title", newNews.NewsTitle);
            parm[1] = new NpgsqlParameter("des", newNews.NewsDescription);

            query = @" INSERT INTO   news(title, description)
                            VALUES   (:title, :des) 
                         Returning   news_id";

            int id=NpgSqlHelper.ExecuteNonQuery(connectionString, CommandType.Text, query, parm);

            return id;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

On executing this function I always get the -1 value

Thanks in advance

While executing the following query on pgAdmin gives correct result:

INSERT INTO news(title, description)
    VALUES ('title','description')
    Returning news_id

2 Answers 2

3

Have you tried NpgsqlCommand.ExecuteScalar or the equivalent for the API you are using?

Sign up to request clarification or add additional context in comments.

2 Comments

Because all I see is NpgSqlHelper.ExecuteNonQuery.
@facebook-100001745831878 well that is probably your problem. ExecuteNonQuery returns The number of rows affected if known; -1 otherwise. Read the link that I posted for ExecuteScalar.
1

Two possibilities I see:

1) the -1 value indicates you are hitting a rollback situation. When you execute the function, check the table: did the record successfully insert or did some other situation cause a rollback? If so, find what is causing the rollback (see #2).

2) the -1 value also can be returned if you are running a non-insert statement. I realize you ARE running an insert, but what about any TRIGGERS on this table? Are you doing any Select statements in the trigger?

Hope this helps.

1 Comment

The fact that the query works in stand-alone fashion indicates the C# is the culprit. I would check parms and again, do the test in #1 above. Are you getting a successful record insertion?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.