2013-01-25 50 views
2

我有一個table.this是我的表腳本: -如何返回自動生成的ID在插入查詢在Postgres的SQL

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; 

現在我想自動插入上的新紀錄產生news_id在桌子裏。

這是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

在此先感謝

在執行上的pgAdmin以下查詢給出正確的結果:

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

回答

3

您是否嘗試過NpgsqlCommand.ExecuteScalar或您正在使用的API的等效項目?

+0

因爲我看到的只是'NpgSqlHelper.ExecuteNonQuery'。 – 2013-01-25 12:20:10

+0

我正在使用NpgsqlCommand.ExecutenonQuery – Suri

+0

@ facebook-100001745831878以及那可能是你的問題。 ExecuteNonQuery返回**受影響的行數(如果已知); -1否則**。閱讀我爲ExecuteScalar發佈的鏈接。 – 2013-01-28 19:22:53

1

我看到兩種可能性:

1)-1值表示您正在回滾情況。當你執行該函數時,請檢查該表:該記錄是否成功插入或執行了其他一些情況會導致回滾?如果是這樣,找到是什麼導致回滾(見#2)。

2)如果您正在運行非插入語句,則也可以返回-1值。我意識到你正在運行一個插入,但這張桌子上的任何觸發器呢?你在觸發器中做任何Select語句嗎?

希望這會有所幫助。

+0

查詢以獨立方式工作的事實表明C#是罪魁禍首。我會再次檢查parms,並在上面的#1中進行測試。你是否獲得了成功的插入記錄? –

相關問題