PostgreSQL
 sql >> Cơ Sở Dữ Liệu >  >> RDS >> PostgreSQL

ánh xạ psycopg2 Python:danh sách các phân đoạn tới Postgres:mảng kiểu kết hợp cho một câu lệnh INSERT

Mở rộng nỗ lực của bạn chỉ một chút thôi, còn:

quote_1 = ("monkeys rock", "False")
quote_2 = ("donkeys rock",  "True")
q_list = [ quote_1, quote_2]
print cur.mogrify("insert into posts VALUES(%s,%s::quotes[])", 
                  ("animals are good", q_list))
#
#                 added explicit cast to quotes[]->^^^^^^^^

Giải thích :

Nếu bạn chạy:

insert into posts 
VALUES('animals are good', ARRAY[
    ('monkeys rock', 'false'),
    ('donkeys rock', 'true')
]);

trực tiếp trong psql bạn sẽ nhận được:

regress=# insert into posts 
regress-# VALUES('animals are good',ARRAY[
regress-#             ('monkeys rock', 'false'),
regress-#             ('donkeys rock', 'true')
regress-#  ]);
ERROR:  column "q" is of type quotes[] but expression is of type record[]
LINE 1: insert into posts VALUES('animals are good',ARRAY[('monkeys ...
                                                    ^
HINT:  You will need to rewrite or cast the expression.

Chắc chắn rồi, nói với Pg rằng mảng ẩn danh của bạn thuộc loại quotes[] thực hiện thủ thuật:

regress=# insert into posts 
regress-# VALUES('animals are good',ARRAY[
regress-#           ('monkeys rock', 'false'),
regress-#           ('donkeys rock', 'true')
regress-# ]::quotes[]);
INSERT 0 1

regress=# select * from posts;
       body       |                           q                            
------------------+--------------------------------------------------------
 animals are good | {"(\"monkeys rock\",false)","(\"donkeys rock\",true)"}
(1 row)



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cách tạm dừng việc thực thi một câu lệnh trong PostgreSQL

  2. Tránh bế tắc PostgreSQL khi thực hiện cập nhật hàng loạt và thao tác xóa

  3. Số sê-ri trên mỗi nhóm hàng cho khóa ghép

  4. Sắp xếp truy vấn chậm theo cột trong bảng đã nối

  5. Làm thế nào để trả về các loại bảng tùy chỉnh từ Npgsql và các thủ tục được lưu trữ?