{"library":"pgcopy","title":"pgcopy","description":"pgcopy is a Python library designed for fast data loading into PostgreSQL databases leveraging the PostgreSQL binary COPY protocol. It supports various database adaptors like psycopg2, psycopg, pg8000, and PyGreSQL, and handles a wide range of PostgreSQL data types, including arrays. The library is currently at version 1.6.2 and focuses on efficient bulk data insertion.","language":"python","status":"active","last_verified":"Thu Apr 16","install":{"commands":["pip install pgcopy"],"cli":null},"imports":["from pgcopy import CopyManager","from pgcopy import Replace"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import os\nfrom datetime import datetime\nfrom pgcopy import CopyManager\nimport psycopg\n\n# Ensure you have a running PostgreSQL instance and a 'weather_db' database\n# You might need to create the database and a 'measurements_table'\n# For example, using `psql -c 'CREATE DATABASE weather_db;'`\n# And inside weather_db: `CREATE TABLE measurements_table (id INT, timestamp TIMESTAMP, location VARCHAR(255), temperature NUMERIC);`\n\ndb_name = os.environ.get('PG_DB_NAME', 'weather_db')\ndb_user = os.environ.get('PG_DB_USER', 'postgres')\ndb_password = os.environ.get('PG_DB_PASSWORD', '')\ndb_host = os.environ.get('PG_DB_HOST', 'localhost')\ndb_port = os.environ.get('PG_DB_PORT', '5432')\n\nconn_string = f\"dbname={db_name} user={db_user} password={db_password} host={db_host} port={db_port}\"\n\ntry:\n    conn = psycopg.connect(conn_string)\n    print(f\"Connected to database: {db_name}\")\n    cursor = conn.cursor()\n\n    # Define columns and records\n    cols = ('id', 'timestamp', 'location', 'temperature')\n    now = datetime.now()\n    records = [\n        (0, now, 'Jerusalem', 72.2),\n        (1, now, 'New York', 75.6),\n        (2, now, 'Moscow', 54.3),\n    ]\n\n    # Use CopyManager for fast insertion\n    mgr = CopyManager(conn, 'measurements_table', cols)\n    mgr.copy(records)\n    conn.commit()\n    print(\"Records copied successfully.\")\n\n    # Verify data (optional)\n    cursor.execute(\"SELECT * FROM measurements_table ORDER BY id;\")\n    print(\"\\nData in table after copy:\")\n    for row in cursor.fetchall():\n        print(row)\n\nfinally:\n    if conn:\n        cursor.close()\n        conn.close()\n        print(\"Database connection closed.\")\n","lang":"python","description":"This quickstart demonstrates how to connect to a PostgreSQL database using `psycopg` (or `psycopg2`), create a `CopyManager` instance, and efficiently insert multiple records using the `copy` method. It emphasizes the importance of committing the transaction after the copy operation. Environment variables are used for database credentials for security and flexibility.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}