简体   繁体   English

如何在PostgreSQL SQL中的插入查询中返回自动生成的ID

[英]How to return auto generated id in insert query in postgres sql

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. 现在,我想在将新记录插入表中时获得自动生成的news_id

This is C# function for insert the news:- 这是用于插入新闻的C#函数:

 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: 在pgAdmin上执行以下查询时,将给出正确的结果:

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

您是否尝试过NpgsqlCommand.ExecuteScalar或您正在使用的API的等效方法?

Two possibilities I see: 我看到两种可能性:

1) the -1 value indicates you are hitting a rollback situation. 1)-1值表示您遇到了回滚情况。 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)。

2) the -1 value also can be returned if you are running a non-insert statement. 2)如果您正在运行非插入语句,也可以返回-1值。 I realize you ARE running an insert, but what about any TRIGGERS on this table? 我知道您正在运行插入,但是此表上的任何TRIGGERS呢? Are you doing any Select statements in the trigger? 您是否在触发器中执行任何Select语句?

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM