douzhun4124 2015-01-08 08:30
浏览 137

Golang PQ SQL驱动程序:批量导入后获取记录ID

Using the pq sql driver for golang, I'm the doing a bulk import as described in the pq docs. Is there a way I can get the ids of the created records?

  • 写回答

1条回答 默认 最新

  • douliedai4838 2016-09-18 23:11
    关注

    I assume that the id column that you are referring to in your COPY statement is based on a serial generation sequence as created by this type of statement:

    CREATE SEQUENCE my_serial_name;
    

    This means that you can query the current value of the id like this:

    SELECT currval('my_serial_name');
    

    Which will return the current value of the id counter.

    As answering any further doubts about this method:

    • this statement is local to the thread and fully isolated,
    • the above statement proves this method to be useful in a multi user environment and will produce correct value not modified by other insert queries performed on tables using this sequence

    For further reading please refer to urls stating that:

    The sequence functions, listed in Table 9-42 (currval included), provide simple, multiuser-safe methods for obtaining successive sequence values from sequence objects.

    https://www.postgresql.org/docs/9.3/static/functions-sequence.html

    Because nextval and setval calls are never rolled back, sequence objects cannot be used if "gapless" assignment of sequence numbers is needed. It is possible to build gapless assignment by using exclusive locking of a table containing a counter; but this solution is much more expensive than sequence objects, especially if many transactions need sequence numbers concurrently.

    https://www.postgresql.org/docs/9.5/static/sql-createsequence.html

    To set the transaction isolation level of a transaction, use the command SET TRANSACTION.

    Important: Some PostgreSQL data types and functions have special rules regarding transactional behavior. In particular, changes made to a sequence (and therefore the counter of a column declared using serial) are immediately visible to all other transactions and are not rolled back if the transaction that made the changes aborts. See Section 9.16 and Section 8.1.4.

    https://www.postgresql.org/docs/9.5/static/transaction-iso.html

    I hope that this answers your question. Postgresql is a great database and can become a very powerful tool when mastered in details. Good luck! :D

    评论

报告相同问题?

悬赏问题

  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算