Using PostgreSQL Database with Python

Using PostgreSQL Database with Python

In this article we will see how to connect to PostgreSQL from Python Script and perform queries.

PostgreSQL is an open source object-relational database management system. PostgreSQL is ACID-compliant and is transactional. It has triggers, foreign keys and supports functions and stored procedures.

PostgreSQL is used by giants like Uber, Apple, Netflix and Instagram.

Requirement:

Create a virtual environment using python 3 and activate it. Install below packages.

psycopg2==2.7.3.2

Installation:

Install the PostgreSQL database and utilities using below commands.

sudo apt-get update
sudo apt-get install postgresql postgresql-contrib

By default, PostgreSQL sets up the user and database “postgres” upon a new installation. We need to switch to this user to use postgres database.

sudo -su postgres

Now go to the Postgres prompt by typing psql on terminal.

We are using version 10.3.

If you get any error in connecting to database, make sure PostgreSQL is running. Check the status using below command.

$ systemctl status postgresql

You can check for errors in logs using below command.

$ tail -f /var/log/postgresql

Creating database:

Before creating a new database, lets list all the databases. Use \l or \list for the same.

To create database, exit the psql terminal by typing \q and use command createdb testdb.

[email protected]:~$ createdb testdb
[email protected]:~$ psql
psql (10.3 (Ubuntu 10.3-1.pgdg16.04+1))
Type "help" for help.

postgres=# \l
                               List of databases
     Name      |  Owner   | Encoding | Collate | Ctype |   Access privileges   
---------------+----------+----------+---------+-------+-----------------------
 postgres      | postgres | UTF8     | en_IN   | en_IN | 
 rana_test     | postgres | UTF8     | en_IN   | en_IN | 
 template0     | postgres | UTF8     | en_IN   | en_IN | =c/postgres          +
               |          |          |         |       | postgres=CTc/postgres
 template1     | postgres | UTF8     | en_IN   | en_IN | =c/postgres          +
               |          |          |         |       | postgres=CTc/postgres
 testdb        | postgres | UTF8     | en_IN   | en_IN | 
(5 rows)

postgres=# \c testdb
You are now connected to database "testdb" as user "postgres".
testdb=# 

To connect to another database, use command \c or \connect and database name. \c testdb in this case.

Creating Table:

Most the query sytanx in PostgreSQL are same as MySQL.

create table users (
    id serial PRIMARY KEY,
    username varchar (20) NOT NULL,
    age smallint NOT NULL,
    location varchar (50) NOT NULL
);

Copy paste the above sytax in terminal and new table will be created. You can list the tables by typing \d.

testdb=# create table users (
testdb(#     username varchar (20) NOT NULL,
testdb(#     age smallint NOT NULL,
testdb(#     location varchar (50) NOT NULL
testdb(# );
CREATE TABLE
testdb=# \d
         List of relations
 Schema | Name  | Type  |  Owner   
--------+-------+-------+----------
 public | users | table | postgres
(1 row)

testdb=# 

You can learn more about querying from psql terminal by visitng official site. Lets go to Python code.

Connecting from Python Script:

We installed the psycopg package in virtual environment. Use below code in Python Script to connect to database.

import psycopg2


# this function will return the connection object
def connect():
    conn = None
    try:
        conn = psycopg2.connect(host="localhost", user="postgres", password="root", database="testdb")
    except Exception as e:
        print(repr(e))

    return conn

Inserting Data into Table:

First get the connection and cursor and then create query. Once query is executed, commit using connection and close the cursor and connection.

conn = connect()
cur = conn.cursor()

last_insert_id = None

# inserting data in users table
sql_query = "insert into users (username, age, location) values (%s, %s, %s) returning id;"

sql_data = (
    "Ajay",
    "25",
    "New York"
)


cur.execute(sql_query, sql_data)
last_insert_id = cur.fetchone()[0]
print("Last Insert ID " + str(last_insert_id))

conn.commit()
cur.close()
conn.close()

return last_insert_id

We are Inserting data in table and returning the primary key id which is the serial key.

Fetching Data from Table:

Select query for PostgreSQL is same as MySQL.

conn = connect()
cur = conn.cursor()

sql_query = "select username, age, location from users where location = %s;"
sql_data = ("Delhi")
cur.execute(sql_query, sql_data)

results = cur.fetchall()
return results

Updating a row:

conn = connect()
cursor = conn.cursor()

sql_query = "update users set location = %s where username = %s;"
sql_data = ("Mumbai", "Ajay")

cursor.execute(sql_query, sql_data)

cursor.close()
conn.close()

return True

To exit the terminal use \q command.

If you are facing any issue, feel free to comment.

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

Python Tutorial for Beginners (2019) - Learn Python for Machine Learning and Web Development

Python Tutorial for Beginners (2019) - Learn Python for Machine Learning and Web Development




TABLE OF CONTENT

00:00:00 Introduction

00:01:49 Installing Python

00:06:10 Your First Python Program

00:08:11 How Python Code Gets Executed

00:11:24 How Long It Takes To Learn Python

00:13:03 Variables

00:18:21 Receiving Input

00:22:16 Python Cheat Sheet

00:22:46 Type Conversion

00:29:31 Strings

00:37:36 Formatted Strings

00:40:50 String Methods

00:48:33 Arithmetic Operations

00:51:33 Operator Precedence

00:55:04 Math Functions

00:58:17 If Statements

01:06:32 Logical Operators

01:11:25 Comparison Operators

01:16:17 Weight Converter Program

01:20:43 While Loops

01:24:07 Building a Guessing Game

01:30:51 Building the Car Game

01:41:48 For Loops

01:47:46 Nested Loops

01:55:50 Lists

02:01:45 2D Lists

02:05:11 My Complete Python Course

02:06:00 List Methods

02:13:25 Tuples

02:15:34 Unpacking

02:18:21 Dictionaries

02:26:21 Emoji Converter

02:30:31 Functions

02:35:21 Parameters

02:39:24 Keyword Arguments

02:44:45 Return Statement

02:48:55 Creating a Reusable Function

02:53:42 Exceptions

02:59:14 Comments

03:01:46 Classes

03:07:46 Constructors

03:14:41 Inheritance

03:19:33 Modules

03:30:12 Packages

03:36:22 Generating Random Values

03:44:37 Working with Directories

03:50:47 Pypi and Pip

03:55:34 Project 1: Automation with Python

04:10:22 Project 2: Machine Learning with Python

04:58:37 Project 3: Building a Website with Django


Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Complete Python Bootcamp: Go from zero to hero in Python 3

Machine Learning A-Z™: Hands-On Python & R In Data Science

Python and Django Full Stack Web Developer Bootcamp

Complete Python Masterclass

Python Programming Tutorial | Full Python Course for Beginners 2019 👍

Top 10 Python Frameworks for Web Development In 2019

Python for Financial Analysis and Algorithmic Trading

Building A Concurrent Web Scraper With Python and Selenium

Develop this one fundamental skill if you want to become a successful developer

Throughout my career, a multitude of people have asked me&nbsp;<em>what does it take to become a successful developer?</em>

Throughout my career, a multitude of people have asked me what does it take to become a successful developer?

It’s a common question newbies and those looking to switch careers often ask — mostly because they see the potential paycheck. There is also a Hollywood level of coolness attached to working with computers nowadays. Being a programmer or developer is akin to being a doctor or lawyer. There is job security.

But a lot of people who try to enter the profession don’t make it. So what is it that separates those who make it and those who don’t? 

Read full article here