Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

postgres fecth python

import psycopg2
import os

'''
* dotenv is a function from load_dotenv whichis used to to store sensitive data in separate file and 
can be accesed using os and loadenv
* psycopg2 is a module to connect postgreSql to python
* can install by using `pip install psycopg2` '''
from dotenv import load_dotenv
load_dotenv()

try:
	conn = psycopg2.connect(
            host=os.getenv('host'),  #localhost/127.0.0.1
            database=os.getenv('database'), #database_name 
            user=os.getenv('user'), #username of db
            password=os.getenv('password')) #password of db
	
	# connection is established and you can use all postgreSql queries using conn
   

    # create tables in the PostgreSQL database
    	create_table_query = (
        """
          	create table TableName (
            id numeric, 
            name VARCHAR(255) NOT NULL,
            )
        """)

    try:
        # define cursor
        cur = conn.cursor()
        # create table (single)
        cur.execute(create_table_query)
        # commit the changes
        conn.commit()
    except (Exception, psycopg2.Error) as error :
    	print ("Error while connecting to PostgreSQL", error)
    finally:
        if conn:
        	cur.close()
		  	conn.close()
			print("connection is closed")


# fetch records from db
    """ insert a new data into the db table """
	
	# Here the tableName refers to the name you used to create table in db

    sql_query = '''SELECT * from tableName;'''
    
    try:
       
        #Creating a cursor object using the cursor() method
        cursor = conn.cursor()

        #Retrieving data
        cursor.execute(sql_query)

        #Fetching 1st row from the table
        # result = cursor.fetchone();
        # print(result)

        # #Fetching all rows from the table
        result = cursor.fetchall();
        # print(result)

        #Commit your changes in the database
        conn.commit()

    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn:
          	conn.close()
            conn.close()
			print("connection is closed")
            
# inserting data to db
 """ insert a new data into the db table """
	# Here the tableName refers to the name you used to create table in db

    insert_query = """INSERT INTO tableName(
								id,
                                name)
     VALUES(%s,%s);"""
    values_to_insert=(1, 'John')
    try:
        #define cursor
        cur = conn.cursor()
        # insert table (single)
        cur.execute(insert_query, values_to_insert)
        # commit the changes
        conn.commit()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn:
          	cur.close()
            conn.close()
            print("connection is closed")
Comment

PREVIOUS NEXT
Code Example
Python :: discord.py main file setup 
Python :: clear notebook output 
Python :: how to close python in terminal 
Python :: ring Loop Command 
Python :: ring Creating a Multi-Dimensional Array using List 
Python :: ring write the same example using normal for loop the Encrypt() and Decrypt() functions. 
Python :: swagger django 
Python :: ring Using the Natural Library 
Python :: ring Trace library usage to pass an error 
Python :: ring Desktop, WebAssembly and Mobile create an application to ask the user about his/her name. 
Python :: equivalent of geom smooth function in python using plotline lib 
Python :: circular ImportError: cannot import name 
Python :: talib 
Python :: what is primary key in python 
Python :: sympy.diff 
Python :: rúllandi veltandi standandi sitjandi 
Python :: how to read then overwrite a file with python with truncate 
Python :: python class overwrite length method 
Python :: how to load images from folder in python 
Python :: how to find largest number in list python without max 
Python :: pls work 
Python :: python run async function without await 
Python :: print start time in python 
Python :: python turn list of strings into list of doubles 
Python :: python geodata visualize 
Python :: python ravel function output 
Python :: python variable type casting 
Python :: save media file from url python 
Python :: Créer un décorateur python 
Python :: python too many values to unpack 
ADD CONTENT
Topic
Content
Source link
Name
6+6 =