<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Sapan Ravidas</title>
    <description>The latest articles on DEV Community by Sapan Ravidas (@sapanravidas).</description>
    <link>https://dev.to/sapanravidas</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F656959%2Fd10ebe22-414d-4a64-8d44-e0aff705e0aa.jpeg</url>
      <title>DEV Community: Sapan Ravidas</title>
      <link>https://dev.to/sapanravidas</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sapanravidas"/>
    <language>en</language>
    <item>
      <title>PostgreSQL With Python3</title>
      <dc:creator>Sapan Ravidas</dc:creator>
      <pubDate>Sun, 27 Jun 2021 12:15:47 +0000</pubDate>
      <link>https://dev.to/sapanravidas/postgresql-with-python3-4dlg</link>
      <guid>https://dev.to/sapanravidas/postgresql-with-python3-4dlg</guid>
      <description>&lt;p&gt;In this post we’ll see how we can interact with our postgres database using python3 application in three different ways ie. psycopg2, SqlAlchemy core and SqlAlchemy ORM. We’ll also look, how we can use Stored Procedure for our transactions.&lt;/p&gt;

&lt;p&gt; &lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;p&gt;To access the databases in python, we often use the given database’s python modules. These modules can have completely different syntax how we interact with them. But since there are so many database systems, then Python created a common specification to follow so the programmers can manage their own databases. These specifications is called the python database API.&lt;/p&gt;

&lt;p&gt;Each module must implement a connect function that returns a connection object. These returned connection object is a connection to the database&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- connection = connect(parameters…)

- connection.commit()

- connection.rollback()

- connection.rollback()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt; &lt;/p&gt;
&lt;h1&gt;
  
  
  Postgres
&lt;/h1&gt;

&lt;p&gt;In postgres, data is organized into tables and also known for highly extensible and standard compliant. It is also object relational database system, including advanced features like table inheritances and function overloading.&lt;/p&gt;

&lt;p&gt;Adheres more closely to SQL standards than MySQL.&lt;/p&gt;

&lt;p&gt;Like MySQL, Postgres follows a client server model, so we need a driver to interact with the database — use Postgres shell or a Postgres GUI.&lt;/p&gt;

&lt;p&gt;First thing first install PostgreSQL in your system. &lt;a href="https://www.postgresql.org/"&gt;https://www.postgresql.org/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then start PostgreSQL in your system. I’m using using ubuntu-20.0. In my case:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ sudo systemctl start postgresql@13-main
$ sudo -u postgres psql
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now our server starts and running, before we create database we need to create a role that we can use to access the database in our python program. PostgreSQL lets you grant permissions directly to the database users. However, as a good practice, it is recommended that you create multiple roles with specific sets of permissions based on application and access requirements. Then assign the appropriate role to each user. The roles should be used to enforce a &lt;strong&gt;least privilege&lt;/strong&gt; model for accessing database objects.&lt;/p&gt;

&lt;p&gt;Users, groups, and roles are the same thing in PostgreSQL. The only difference is that being that users have permission to log in by default. The roles are used only to group grants and other roles. This role can then be assigned to one or more users to grant them all the permissions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE ROLE &amp;lt;user&amp;gt; WITH LOGIN PASSWORD &amp;lt;password&amp;gt;;
ALTER ROLE &amp;lt;user&amp;gt; WITH CREATEDB;

expample:

CREATE ROLE postgres WITH LOGIN PASSWORD 'lgwmpsc';
ALTER ROLE postgres WITH CREATEDB;

-- In this case we have provided a privilege to create databases to the specific user.
-- Note: If you're creating role with name other than 'postgres' you have to create database with the same name.
-- We can see the list of users or roles with syntax

\du 

or 

\du+ 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Login to PostgreSQL with user and password.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- To view the list of databases use\list
-- To connect to the database use 

\c &amp;lt;database-name&amp;gt;

-- to view the list of the table in that particular database

\dt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--tv5cRTbZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/226fdxk1b86bu5kd45lc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--tv5cRTbZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/226fdxk1b86bu5kd45lc.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;h1&gt;
  
  
  PostgreSQL with psycopg2 module
&lt;/h1&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install psycopg2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we’ll see how we can connect with our database using python&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import psycopg2

connection = psycopg2.connect(
    database="store",
    user="sapan",
    password="lgwmfpsc",
    host="localhost",
    port="5432",
    )

# We need cursor for execution of SQL queries
cursor = connection.cursor()
cursor.execute('''CREATE TABLE store
               (Id INT PRIMARY KEY,
               City TEXT,
               Category TEXT,
               SubCategory TEXT,
               Sales REAL,
               Quantity INT, 
               Discount REAL,
               Profit REAL);'''
            )

connection.commit()
connection.close()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--p9ymATvv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/07mifddsaz7r29zbzc5h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--p9ymATvv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/07mifddsaz7r29zbzc5h.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import psycopg2

# I'm passing cinnection object for instant commit
def insert_data(connection, id, city, category, subcategory,
                sales, quantity, discount, profit):
    data_tuple = (id, city, category, subcategory, sales, quantity, discount, profit)

    cursor = connection.cursor()
    cursor.execute('''INSERT INTO store 
                   (Id, City, Category, SubCategory, Sales, Quantity, Discount, Profit)
                   VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
                   ''', data_tuple)

    connection.commit()

    # to confirm that data is inserted
    cursor.execute("SELECT * FROM store;")
    results = cursor.fetchall()
    for row in results:
        print(row)


if __name__ == '__main__':
    connection = psycopg2.connect(
        user = "sapan",
        password = "lgwmfpsc",
        database = "store",
        port = 5432,
        host= "localhost"
        )

    insert_data(connection, 1, 'Miami', 'Furniture', 'Chairs', 267.67, 3, 0.2, 35)
    connection.close()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--81jdCQnC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6q4y9iusp8h9236qz8wp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--81jdCQnC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6q4y9iusp8h9236qz8wp.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt; &lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h1&gt;
  
  
  PostgreSQL with SqlAlchemy Core
&lt;/h1&gt;

&lt;p&gt;We will work with a new database flowers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from sqlalchemy import (create_engine, Table, MetaData,
                        Column, Integer, String, Float)

# the engine allows your apllication to have multiple database connections
# and it manages those connections. From engine with can create a databse 
# connection which can be used to execute database queries on

engine = create_engine('postgres://sapan:lgwmfpsc@localhost/flowers')

# the benifit of connection with 'with' block is- as the block ends
# connection gets closed
with engine.connect() as connection:
    # grap the metadata
    meta = MetaData(engine)

    iris = Table('iris', meta, 
                 Column('id', Integer, primary_key=True), 
                 Column('sepallength', Float), 
                 Column('sepalwidth', Float),
                 Column('petallength', Float),
                 Column('petalwidth', Float)
                 )
    meta.create_all(engine)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--El9vTrFo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iofm67thc2nwkmnl4dgg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--El9vTrFo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iofm67thc2nwkmnl4dgg.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In above we see, how we can create a blank relation in our database.&lt;/p&gt;

&lt;p&gt;Now we’ll learn see how we can perform SQL queries in the relation which is already created.&lt;/p&gt;

&lt;p&gt;I’ll populate the data in the relation from csv file. For different methods of populating data &lt;a href="https://dev.to/sapanravidas/different-ways-to-load-data-from-csv-files-in-postgresql-5hl0"&gt;click here&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from sqlalchemy import create_engine
from sqlalchemy import Table, MetaData

engine = create_engine('postgres://postgres:lgwmfpsc@localhost/flowers')

with engine.connect() as connection:
    # grap some metadata
    meta = MetaData(engine)

    # load the data from the database
    iris_table = Table('iris', meta, autoload = True, autoload_with = engine)

    insert_statement = iris_table.insert().values(
        sepallength = 4.2,
        sepalwidth = 3.2, 
        petallength = 1.1,
        petalwidth = 0.1,
        species = 'Iris-verginia'
        )

    connection.execute(insert_statement)

    # reading first 10 entries
    print("reading first 10 entries\n----------------")
    select_statement = iris_table.select().limit(10)
    result_set = connection.execute(select_statement)
    for row in result_set:
        print(row)


    # select using where clause
    print("\nselect using where clause\n-------------------")
    select_statement = iris_table.select().where(iris_table.c.id == 151)
    result_set = connection.execute(select_statement)
    for row in result_set:
        print(row)

    # update
    print("\n update \n-----------------")
    update_statement = iris_table.update().where(iris_table.c.id == 151).values(sepallength = 4.9, petalwidth = 0.3)
    connection.execute(update_statement)

    print("\nselect using where clause\n-------------------")
    select_statement = iris_table.select().where(iris_table.c.id == 151)
    result_set = connection.execute(select_statement)
    for row in result_set:
        print(row)

    # delet statement
    print("\n delete \n--------------")
    delete_statement = iris_table.delete().where(iris_table.c.id == 151)
    result_set = connection.execute(delete_statement)

    # confirm delete
    print("confim delete")
    not_found_set = connection.execute(select_statement)
    print(not_found_set.rowcount)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--RRJizTWH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fq2rzmqlnd0r2iqdj9xx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--RRJizTWH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fq2rzmqlnd0r2iqdj9xx.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;h1&gt;
  
  
  PostgreSQL with SqlAlchemy ORM
&lt;/h1&gt;

&lt;p&gt;The SQLAlchemy Object Relational Mapper (ORM) presents a method of associating user-defined Python classes with database tables, and instances of those classes (objects) with rows in their corresponding tables.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('postgres://sapan:lgwmfpsc@localhost:5432/books')

# Classes mapped using the Declarative system are defined in terms of a base class which maintains
# a catalog of classes and tables relative to that base - this is known as the declarative base class.
Base = declarative_base()

class Author(Base):
    __tablename__ = 'authors'

    id = Column(Integer, primary_key=True, autoincrement=True)
    first_name = Column(String(length=50))
    last_name = Column(String(length = 50))

    def __repr__(self):
        return f"&amp;lt;Author(id='{self.id}', first_name='{self.first_name}', last_name='{self.last_name}')&amp;gt;"


class Book(Base):
    __tablename__ = 'books'

    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(length =50))
    n_pages = Column(Integer, nullable=False)

    def __repr__(self):
        return f"&amp;lt;Author(id='{self.id}', title='{self.title}', n_pages='{self.n_pages}')&amp;gt;"


class AuthorBook(Base):
    __tablename__ = 'authorbooks'

    id = Column(Integer, primary_key=True, autoincrement=True)
    author_id = Column(Integer, ForeignKey('authors.id'))  
    book_id = Column(Integer, ForeignKey('books.id'))

    author = relationship("Author")
    book = relationship("Book")

    def __repr__(self):
        return f"&amp;lt;AuthorBook(id='{self.id}', author_id='{self.author_id}', book_id='{self.book_id}')&amp;gt;"


Base.metadata.create_all(engine)

def create_session():
    session = sessionmaker(bind=engine)
    return session()


def add_book(title, n_pages, first_name, last_name):
    book = Book(title = title, n_pages = n_pages)

    session = create_session()
    try:
        existing_author = session.query(Author).filter(Author.first_name == first_name, Author.last_name == last_name).first()
        session.add(book)

        if existing_author:
            session.flush() # we need to book id to be populated to the pairing
            pairing = AuthorBook(author_id = existing_author.id, book_id = book.id)
        else:
            author = Author(first_name = first_name, last_name = last_name)
            session.add(author)
            session.flush()
            pairing = AuthorBook(author_id = author.id, book_id = book.id)

        session.add(pairing)
        session.commit()
        print(pairing)
    except:
        session.rollback()
        raise 
    finally:
        session.close()


if __name__ == '__main__':
    print("Input new book detail after '?':\n------------")
    title = input("titile of the book? ")
    n_pagess = int(input("number of pages in book? "))
    first_name = input("author's first name? ")
    last_name = input("autho's last_name? ")

    add_book(title, n_pagess, first_name, last_name)
    print("done!")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Foreign Key in AuthorBooks model is for the relations in the database and ‘relationship’ is for the Models in our Python application. Both are need for the connection in our relations.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--kv6k4_S3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j5vro6zyfxmsk3712eqw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--kv6k4_S3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j5vro6zyfxmsk3712eqw.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--5zSe5N01--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lv7v6qg8nyagy0l4hv2d.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--5zSe5N01--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lv7v6qg8nyagy0l4hv2d.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;h1&gt;
  
  
  Stored Procedure
&lt;/h1&gt;

&lt;p&gt;A drawback of user-defined functions is that they cannot perform transactions.&lt;/p&gt;

&lt;p&gt;PostgreSQL 11 introduced stored procedures that support transactions.&lt;/p&gt;

&lt;p&gt;When working with databases in python you may want to call a stored procedure associate wit your database to extract database operations.&lt;/p&gt;

&lt;p&gt;A stored procedure is prepared SQL code that usually consists of several SQL statements that are saved and reused.&lt;/p&gt;

&lt;h2&gt;
  
  
  Benfits of stored procedure
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;imporve database performace &lt;/li&gt;
&lt;li&gt;Separate database and application functionality&lt;/li&gt;
&lt;li&gt;Provide a common interface&lt;/li&gt;
&lt;li&gt;Before postgres 11, the only way to create a stored procedure was with a Postgres functions&lt;/li&gt;
&lt;li&gt;function don not support transactions&lt;/li&gt;
&lt;li&gt;With postgres 11 and up we create pocedure that do supoort transactions&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Lets create a stored procedure in Postgres
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;We'll use postgres shell, not python&lt;/li&gt;
&lt;li&gt;stored procedure are associated with database, not application.&lt;/li&gt;
&lt;li&gt;our python application just call the stored procedure.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;make sure you have stored procedure functionality in your dbms&lt;br&gt;
using&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;\n CREATE PROCEDURE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE OR REPLACE PROCEDURE &amp;lt;name-of-procedure&amp;gt; (&amp;lt;data-type&amp;gt;, &amp;lt;data-type&amp;gt;) 
LANGUAGE &amp;lt;language&amp;gt; SET ......

example:

CREATE OR REPLACE PROCEDURE retured_reduce_sepallength(INT, REAL) 
LANGUAGE plpgsql 
AS $$ 
BEGIN 
UPDATE iris 
SET sepallengthcm = sepallengthcm - $2, petalwidthcm = petalwidthcm + $2  
WHERE id = $1; 
COMMIT;
END;
$$;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;AS separates the heading and the body of the stored procedure.&lt;/p&gt;

&lt;p&gt;$$ indicates the start of the body procedure.&lt;/p&gt;

&lt;p&gt;Before, we write the implementation of the procedure, it’s good practice to surround the implementation with begin and end, so its treated as transaction.&lt;/p&gt;

&lt;p&gt;Call the stored procedure&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CALL retured_reduce_sepallength(154, 1.2);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import psycopg2

if __name__ == '__main__':
    conn = psycopg2.connect(
        database = "flowers",
        user = "postgres",
        password = "lgwmfpsc",
        host = "localhost",
        port = "5432"
        )

    # Since we're moving our commit to the transaction layer (stored procedure)'
    # rather having in application layer
    conn.autocommit = True
    cursor = conn.cursor()

    cursor.execute('''CALL retured_reduce_sepallength(%s, %s)''', (152, 1))
    # callproc is used for postgress functions, not for postgres procedures. But at 
    # the time API has not been updated, so we will use this
    # How to call a function : cursor.callproc('retured_reduce_sepallength', (152, 1))


    conn.close()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from sqlalchemy import create_engine
from sqlalchemy import Table, MetaData

engine = create_engine(
    'postgres://postgres:lgwmfpsc@localhost/flowers',
    isolation_level="AUTOCOMMIT"
    )

# autocommit sometimes a bit tricky. If you want to perform a trasaction in python app 
# layer, you have set this AUTOCOMMIT to false

with engine.connect() as connection:
    meta = MetaData(engine)
    iris_table = Table('iris', meta, autoload=True, autoload_with=engine)

    # connection.execute('COMMIT')
    connection.execute("CALL retured_reduce_sepallength(%s, %s)", (151, 1))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine  = create_engine(
    'postgres://postgres:lgwmfpsc@localhost/flowers',
    # isolation_level = "AUTOCOMMIT"
    )
Base = declarative_base(engine)
Base.metadata.reflect(engine)

class Iris(Base):
    __table__ = Base.metadata.tables['iris']

    def __repr__(self):
        return f"""&amp;lt;Iris(id='{self.id}', sepalLength='{self.sepallengthcm}', sepalWidth='{self.sepalwidthcm}', petalLength='{self.petallengthcm}', petalWidth='{self.petalwidthcm}')&amp;gt;"""


if __name__ == '__main__':
    with engine.connect() as connection:
        connection.execute("COMMIT")
        connection.execute("CALL retured_reduce_sepallength(%s, %s)", (150, 1))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can run this scripts and simultaneously check the data in postgres shell.&lt;/p&gt;

&lt;h1&gt;
  
  
  END
&lt;/h1&gt;

</description>
    </item>
    <item>
      <title>Different Ways to Load Data From CSV Files in PostgreSQL</title>
      <dc:creator>Sapan Ravidas</dc:creator>
      <pubDate>Sun, 27 Jun 2021 12:04:15 +0000</pubDate>
      <link>https://dev.to/sapanravidas/different-ways-to-load-data-from-csv-files-in-postgresql-5hl0</link>
      <guid>https://dev.to/sapanravidas/different-ways-to-load-data-from-csv-files-in-postgresql-5hl0</guid>
      <description>&lt;h1&gt;
  
  
  Populating data
&lt;/h1&gt;

&lt;p&gt;First of all make sure that your user has SUPERUSER privileges.&lt;br&gt;
You can set this using.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ALTER ROLE &amp;lt;user&amp;gt; WITH SUPERUSER;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Here we'll see three ways to populate our data
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;using inbuilt csv module&lt;/li&gt;
&lt;li&gt;using SQL CALL&lt;/li&gt;
&lt;li&gt;using pandas&lt;/li&gt;
&lt;/ul&gt;



&lt;h2&gt;
  
  
  1. Using CSV module
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import psycopg2 
import csv

connection = psycopg2.connect(
    database="store", 
    user="postgres",
    password="lgwmfpsc", 
    host="localhost",
    port="5432", # default post
    )

cursor = connection.cursor()

cursor.execute("DROP TABLE IF EXISTS superstore;")
connection.commit()

create_query = '''CREATE TABLE superstore (
    id INT PRIMARY KEY,
    ship_model VARCHAR(255) NOT NULL,
    segment VARCHAR(255) NOT NULL,
    country VARCHAR(255) NOT NULL,
    city VARCHAR(255) NOT NULL,
    state VARCHAR(255) NOT NULL,
    postal_code INT NOT NULL,
    region VARCHAR(255) NOT NULL,
    category VARCHAR(255) NOT NULL,
    subcategory VARCHAR(255) NOT NULL,
    sales FLOAT NOT NULL,
    quantity INT NOT NULL,
    discount FLOAT NOT NULL,
    profit FLOAT NOT NULL
    )
'''

cursor.execute(create_query)
connection.commit()

with open('./SampleSuperstore.csv') as file:
    id = 1
    csv_data = csv.reader(file)
    next(csv_data)
    for row in csv_data:
        row = [id] + row
        row_tuple = tuple(row)
        cursor.execute('''INSERT INTO superstore (id, ship_model, segment, country, city, state, postal_code,
                       region, category, subcategory, sales, quantity, discount, profit)
                       VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''', row_tuple)
        id += 1

connection.commit()

cursor.execute("SELECT * FROM superstore LIMIT 10")
print(cursor.fetchall())

connection.close()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before iterating throught the list next is used to skip the first line of the file as they are headers.&lt;/p&gt;



&lt;h2&gt;
  
  
  2. Using SQL CALL
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import psycopg2
import csv

connection = psycopg2.connect(
    user = 'postgres',
    password = 'lgwmfpsc', 
    host = 'localhost',
    database = 'store', 
    port="5432"
    )

cursor = connection.cursor()

create_query = '''CREATE TABLE superstore (
    id INT(255) NOT NULL AUTO_INCREMENT,
    ship_model VARCHAR(255) NOT NULL,
    segment VARCHAR(255) NOT NULL,
    country VARCHAR(255) NOT NULL,
    city VARCHAR(255) NOT NULL,
    state VARCHAR(255) NOT NULL,
    postal_code INT NOT NULL,
    region VARCHAR(255) NOT NULL,
    category VARCHAR(255) NOT NULL,
    subcategory VARCHAR(255) NOT NULL,
    sales FLOAT NOT NULL,
    quantity INT NOT NULL,
    discount FLOAT NOT NULL,
    profit FLOAT NOT NULL,
    PRIMARY KEY(id))
'''



cursor.execute("DROP TABLE IF EXISTS superstore")
cursor.execute(create_query)

q = '''LOAD DATA LOCAL INFILE '/home/sapan/codes/Linkedin-Python/database-python/csv-database/SampleSuperstore.csv'
    INTO TABLE superstore
    FIELDS TERMINATED BY ',' ENCLOSED BY "" (ship_model, segment, country, city, state, postal_code,
    region, category, subcategory, sales, quantity, discount, profit);'''

cursor.execute(q)

connection.commit()

cursor.execute("SELECT * FROM superstore LIMIT 10")
print(cursor.fetchall())

connection.close()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbk2yw3ktn670hfoilr6k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbk2yw3ktn670hfoilr6k.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;



&lt;h2&gt;
  
  
  3. Usinng pandas
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# using pandas with sqlalchemy

import pandas as pd
from sqlalchemy import Column, Integer, String, DateTime, Float, Boolean
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('postgres://postgres:lgwmfpsc@localhost/store')

Base = declarative_base()

class SalesReport(Base):
    __tablename__ = 'salesreport'

    id = Column(Integer, primary_key=True)
    country = Column("Country", String(length=50))
    state = Column("State", String(length=50))
    city = Column("City", String(length=50))
    postalcode = Column("Postal Code", String(length=50))

    def __repr__(self):
        return f'''&amp;lt;Salesreport(id='{self.country}', country='{self.country}', state='{self.state}', postal_code='{self.postalcode}')&amp;gt;
    '''    

Base.metadata.create_all(engine)

file_name = './sample_data.csv'
data_frame = pd.read_csv(file_name)

# # the below function call automatically import the data into our database, so we do not
# # to work with the session here
data_frame.to_sql(
    con = engine,
    name = SalesReport.__tablename__, 
    if_exists='append', 
    index = False
    )

# # however if we want to prove the data was imported, we need session here
session = sessionmaker()
session.configure(bind=engine)
s = session()

results = s.query(SalesReport).limit(10).all()
for i, r in enumerate(results):
    print(i, r)
    print()


overall_max = s.query(func.max(SalesReport.postalcode)).scalar
print(overall_max) 

results = s.query(SalesReport).order_by(SalesReport.postalcode.desc()).limit(10)
for row in results:
    print(results)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuioqpxuu3t1fgu76dugy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuioqpxuu3t1fgu76dugy.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F246tjbk4vhzludkms7k9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F246tjbk4vhzludkms7k9.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this post we only see how to populate our data. If you want to view completed details how to use postgreSQL with python refers to this article.&lt;br&gt;
&lt;a href="https://sapanravidas.medium.com/postgres-with-python3-ec3cafc5c98d" rel="noopener noreferrer"&gt;https://sapanravidas.medium.com/postgres-with-python3-ec3cafc5c98d&lt;/a&gt;&lt;/p&gt;



&lt;h1&gt;
  
  
  END
&lt;/h1&gt;

</description>
      <category>postgres</category>
      <category>python</category>
      <category>sql</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
