Inserting array values

前端 未结 1 1777
广开言路
广开言路 2021-02-05 01:55

How do I write and execute a query which inserts array values using libpqxx?

INSERT INTO exampleTable(exampleArray[3]) VALUES(\'{1, 2, 3}\');

T

相关标签:
1条回答
  • 2021-02-05 02:43

    You should use a column name without an index to insert an array:

    create table example(arr smallint[]);
    insert into example(arr) values('{1, 2, 3}');
    -- alternative syntax
    -- insert into example(arr) values(array[1, 2, 3]);
    
    select * from example;
    
       arr   
    ---------
     {1,2,3}
    (1 row) 
    

    Use the column name with an index to access a single element of the array:

    select arr[2] as "arr[2]"
    from example;
    
     arr[2] 
    --------
          2
    (1 row)
    
    update example set arr[2] = 10;
    select * from example;
    
       arr    
    ----------
     {1,10,3}
    (1 row) 
    

    You can use arr[n] in INSERT but this has special meaning. With this syntax you can create an array with one element indexed from the given number:

    delete from example;
    insert into example(arr[3]) values (1);
    select * from example;
    
        arr    
    -----------
     [3:3]={1}
    (1 row) 
    

    As a result you have an array which lower bound is 3:

    select arr[3] from example;
     arr 
    -----
       1
    (1 row)
    
    0 讨论(0)
提交回复
热议问题