{"id":18417278,"url":"https://github.com/kishlayjeet/connect-postgresql-database-to-python","last_synced_at":"2025-04-14T18:41:54.171Z","repository":{"id":108295252,"uuid":"572121581","full_name":"kishlayjeet/Connect-PostgreSQL-database-to-Python","owner":"kishlayjeet","description":"This repository is to show you how you can connect your PostgreSQL database to your python.","archived":false,"fork":false,"pushed_at":"2023-11-25T16:36:26.000Z","size":4,"stargazers_count":3,"open_issues_count":1,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-28T07:11:18.500Z","etag":null,"topics":["postgres","postgresql","postgresql-connect-python","postgresql-connector","postgresql-database","postgresql-python","psycopg2","sql"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kishlayjeet.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-11-29T15:44:06.000Z","updated_at":"2022-12-03T05:33:10.000Z","dependencies_parsed_at":"2024-12-24T17:11:37.316Z","dependency_job_id":"6abfdd9e-fc71-448f-ac13-017be1ff46f1","html_url":"https://github.com/kishlayjeet/Connect-PostgreSQL-database-to-Python","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kishlayjeet%2FConnect-PostgreSQL-database-to-Python","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kishlayjeet%2FConnect-PostgreSQL-database-to-Python/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kishlayjeet%2FConnect-PostgreSQL-database-to-Python/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kishlayjeet%2FConnect-PostgreSQL-database-to-Python/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kishlayjeet","download_url":"https://codeload.github.com/kishlayjeet/Connect-PostgreSQL-database-to-Python/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248938282,"owners_count":21186378,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["postgres","postgresql","postgresql-connect-python","postgresql-connector","postgresql-database","postgresql-python","psycopg2","sql"],"created_at":"2024-11-06T04:08:48.796Z","updated_at":"2025-04-14T18:41:54.163Z","avatar_url":"https://github.com/kishlayjeet.png","language":"Python","readme":"# Connect PostgreSQL Database with Python\n\nThis tutorial explains how to connect your PostgreSQL database to Python and query it.\n\n## Prerequisites\n\nBefore you begin, make sure you have the following installed:\n\n- Python: You can download and install Python from the official website (https://www.python.org).\n- PostgreSQL: Install PostgreSQL on your computer by following the instructions from the official website (https://www.postgresql.org).\n\n## Install the \"psycopg2\" Package\n\nTo access the PostgreSQL database, Python needs a PostgreSQL driver. You can install the `psycopg2` package using pip, the Python package installer. Open your command prompt or terminal and run the following command:\n\n```bash\npip install psycopg2\n```\n\n## Import the \"psycopg2\" Library\n\nTo use the `psycopg2` package in your Python code, import the `psycopg2` module:\n\n```python\nimport psycopg2\n```\n\n## Creating a Database\n\nFor the purpose of this example, we will need a sample database. Follow the steps below to create it:\n\n1. Open a PostgreSQL client tool like `pgadmin4` or `psql`.\n2. Log in to the database using your credentials.\n3. Run the following command to create a database, for example, `company`:\n\n```sql\nCREATE DATABASE company;\n```\n\n## Create Connection\n\nTo connect to the previously created database (`company`), we use the `connect()` function. Establish a connection to the database by providing your PostgreSQL database's username, password, and database name in the Python code:\n\n```python\nmydb = psycopg2.connect(\n  host=\"localhost\",\n  user=\"yourUsername\",\n  password=\"yourPassword\",\n  database=\"company\"\n)\n```\n\n## Create a Cursor\n\nYou need to create a cursor to execute SQL queries in your Python code:\n\n```python\nmycursor = mydb.cursor()\n```\n\nNow you can use SQL commands to query the database.\n\n## Commit Changes\n\nYou also need to include the commit function and set the automatic commit to be `True`:\n\n```python\nmydb.set_session(autocommit=True)\n```\n\nThis ensures that each action is committed or saved without having to call `mydb.commit()` after each command.\n\n## Query the Database\n\nNow, let's create a table in the database using the cursor we created:\n\n```python\nmycursor.execute('''CREATE TABLE employee(\n    EmployeeID int,\n    Name varchar(255),\n    Email varchar(255));\n''')\n```\n\n## Insert Data Into Table\n\nNow, let's insert values into the database:\n\n```python\nmycursor.execute('''\nINSERT INTO employee (EmployeeID, Name, Email)\n    VALUES (101, 'Mark', 'mark@company.com'),\n           (102, 'Robert', 'robert@company.com'),\n           (103, 'Spencer', 'spencer@company.com');\n''')\n```\n\n## Retrieve the Data\n\nLet's query the database:\n\n```python\nmycursor.execute(\"SELECT * FROM employee\")\n```\n\nAfter executing the query, you can use one of the `psycopg2` functions to retrieve data rows:\n\n- `fetchone()`: Retrieves exactly one row (the first row) after executing the SQL query.\n- `fetchall()`: Retrieves all the rows.\n- `fetchmany()`: Retrieves a specific number of rows.\n\nFor example:\n\n```python\nprint(mycursor.fetchone())\n```\n\nOutput:\n\n| EmployeeID | Name | Email            |\n| :--------- | :--- | :--------------- |\n| 101        | Mark | mark@company.com |\n\nThe most basic way to fetch data from your database is to use the `fetchone()` function. It returns exactly one row (the first row) after executing the SQL query.\n\n```python\n\n\nprint(mycursor.fetchall())\n```\n\nOutput:\n\n| EmployeeID | Name    | Email               |\n| :--------- | :------ | :------------------ |\n| 101        | Mark    | mark@company.com    |\n| 102        | Robert  | robert@company.com  |\n| 103        | Spencer | spencer@company.com |\n\nIf you need more than one row from your database, you can use `fetchall()`, which returns all the rows.\n\n```python\nprint(mycursor.fetchmany(2))\n```\n\nOutput:\n\n| EmployeeID | Name   | Email              |\n| :--------- | :----- | :----------------- |\n| 101        | Mark   | mark@company.com   |\n| 102        | Robert | robert@company.com |\n\nWith `fetchmany()`, you have another option to retrieve a specific number of rows from the database.\n\nChoose the appropriate function based on your needs.\n\n## Close the Connection\n\nFinally, remember to close the cursor and the connection:\n\n```python\nmycursor.close()\nmydb.close()\n```\n\nYou can also find the code snippet [here](https://github.com/kishlayjeet/Connect-PostgreSQL-database-to-Python/blob/d7c5cae0a809ec0714cf193c5db6a77f30e70502/code-snippet.py).\n\n## Authors\n\nThis tutorial was written by [Kishlay \nJeet](https://www.github.com/kishlayjeet), with contributions from other people.\nIf you encounter any issues with this tutorial, please let me know, and I will make improvements.\nIf you found this tutorial helpful, please consider giving it a star.\n\n## Feedback\n\nIf you have any feedback, please reach out to me at contact.kishlayjeet@gmail.com.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkishlayjeet%2Fconnect-postgresql-database-to-python","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkishlayjeet%2Fconnect-postgresql-database-to-python","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkishlayjeet%2Fconnect-postgresql-database-to-python/lists"}