PostgreSQL – Useful Resources

PostgreSQL – Useful Resources ”; Previous Next The following resources contain additional information on PostgreSQL. Please use them to get more in-depth knowledge on this topic. Useful Video Courses PostgreSQL Databases Course With PgAdmin For Beginners Best Seller 24 Lectures 1.5 hours John Elder More Detail Google BigQuery & PostgreSQL Course : Big Query for Data Analysis 127 Lectures 10.5 hours Abhishek And Pukhraj More Detail Angular 12, Python Django and PostgreSQL Full Stack Web Development 5 Lectures 52 mins Vinay Kumar More Detail Web Scraping APIs for Data Science 2021 | PostgreSQL+Excel 21 Lectures 4 hours AlexanderSchlee More Detail API Scraping – Web Scraping Real Estate Data + PostgreSQL Most Popular 7 Lectures 1 hours AlexanderSchlee More Detail API Scraping – E-Commerce Data – Excel & PostgreSQL 6 Lectures 1 hours AlexanderSchlee More Detail Print Page Previous Next Advertisements ”;

PostgreSQL – PHP

PostgreSQL – PHP Interface ”; Previous Next Installation The PostgreSQL extension is enabled by default in the latest releases of PHP 5.3.x. It is possible to disable it by using –without-pgsql at compile time. Still you can use yum command to install PHP -PostgreSQL interface − yum install php-pgsql Before you start using the PHP PostgreSQL interface, find the pg_hba.conf file in your PostgreSQL installation directory and add the following line − # IPv4 local connections: host all all 127.0.0.1/32 md5 You can start/restart the postgres server, in case it is not running, using the following command − [root@host]# service postgresql restart Stopping postgresql service: [ OK ] Starting postgresql service: [ OK ] Windows users must enable php_pgsql.dll in order to use this extension. This DLL is included with Windows distributions in the latest releases of PHP 5.3.x For detailed installation instructions, kindly check our PHP tutorial and its official website. PHP Interface APIs The following are important PHP routines, which can suffice your requirement to work with PostgreSQL database from your PHP program. If you are looking for a more sophisticated application, then you can look into the PHP official documentation. S. No. API & Description 1 resource pg_connect ( string $connection_string [, int $connect_type ] ) This opens a connection to a PostgreSQL database specified by the connection_string. If PGSQL_CONNECT_FORCE_NEW is passed as connect_type, then a new connection is created in case of a second call to pg_connect(), even if the connection_string is identical to an existing connection. 2 bool pg_connection_reset ( resource $connection ) This routine resets the connection. It is useful for error recovery. Returns TRUE on success or FALSE on failure. 3 int pg_connection_status ( resource $connection ) This routine returns the status of the specified connection. Returns PGSQL_CONNECTION_OK or PGSQL_CONNECTION_BAD. 4 string pg_dbname ([ resource $connection ] ) This routine returns the name of the database that the given PostgreSQL connection resource. 5 resource pg_prepare ([ resource $connection ], string $stmtname, string $query ) This submits a request to create a prepared statement with the given parameters and waits for completion. 6 resource pg_execute ([ resource $connection ], string $stmtname, array $params ) This routine sends a request to execute a prepared statement with given parameters and waits for the result. 7 resource pg_query ([ resource $connection ], string $query ) This routine executes the query on the specified database connection. 8 array pg_fetch_row ( resource $result [, int $row ] ) This routine fetches one row of data from the result associated with the specified result resource. 9 array pg_fetch_all ( resource $result ) This routine returns an array that contains all rows (records) in the result resource. 10 int pg_affected_rows ( resource $result ) This routine returns the number of rows affected by INSERT, UPDATE, and DELETE queries. 11 int pg_num_rows ( resource $result ) This routine returns the number of rows in a PostgreSQL result resource for example number of rows returned by SELECT statement. 12 bool pg_close ([ resource $connection ] ) This routine closes the non-persistent connection to a PostgreSQL database associated with the given connection resource. 13 string pg_last_error ([ resource $connection ] ) This routine returns the last error message for a given connection. 14 string pg_escape_literal ([ resource $connection ], string $data ) This routine escapes a literal for insertion into a text field. 15 string pg_escape_string ([ resource $connection ], string $data ) This routine escapes a string for querying the database. Connecting to Database The following PHP code shows how to connect to an existing database on a local machine and finally a database connection object will be returned. <?php $host = “host = 127.0.0.1”; $port = “port = 5432”; $dbname = “dbname = testdb”; $credentials = “user = postgres password=pass123”; $db = pg_connect( “$host $port $dbname $credentials” ); if(!$db) { echo “Error : Unable to open databasen”; } else { echo “Opened database successfullyn”; } ?> Now, let us run the above given program to open our database testdb: if the database is successfully opened, then it will give the following message − Opened database successfully Create a Table The following PHP program will be used to create a table in a previously created database − <?php $host = “host = 127.0.0.1”; $port = “port = 5432”; $dbname = “dbname = testdb”; $credentials = “user = postgres password=pass123”; $db = pg_connect( “$host $port $dbname $credentials” ); if(!$db) { echo “Error : Unable to open databasen”; } else { echo “Opened database successfullyn”; } $sql =<<<EOF CREATE TABLE COMPANY (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL); EOF; $ret = pg_query($db, $sql); if(!$ret) { echo pg_last_error($db); } else { echo “Table created successfullyn”; } pg_close($db); ?> When the above given program is executed, it will create COMPANY table in your testdb and it will display the following messages − Opened database successfully Table created successfully INSERT Operation The following PHP program shows how we can create records in our COMPANY table created in above example − <?php $host = “host=127.0.0.1”; $port = “port=5432”; $dbname = “dbname = testdb”; $credentials = “user = postgres password=pass123”; $db = pg_connect( “$host $port $dbname $credentials” ); if(!$db) { echo “Error : Unable to open databasen”; } else { echo “Opened database successfullyn”; } $sql =<<<EOF INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, ”Paul”, 32, ”California”, 20000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, ”Allen”, 25, ”Texas”, 15000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, ”Teddy”, 23, ”Norway”, 20000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, ”Mark”, 25, ”Rich-Mond ”, 65000.00 ); EOF; $ret = pg_query($db, $sql); if(!$ret) { echo pg_last_error($db); } else { echo “Records created successfullyn”; } pg_close($db); ?> When the above given program is executed, it will create the given records in COMPANY table and will display the following two lines − Opened database successfully Records created successfully SELECT Operation The following PHP program shows how we can fetch and display records

PostgreSQL – Quick Guide

PostgreSQL – Quick Guide ”; Previous Next PostgreSQL – Overview PostgreSQL is a powerful, open source object-relational database system. It has more than 15 years of active development phase and a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness. This tutorial will give you a quick start with PostgreSQL and make you comfortable with PostgreSQL programming. What is PostgreSQL? PostgreSQL (pronounced as post-gress-Q-L) is an open source relational database management system (DBMS) developed by a worldwide team of volunteers. PostgreSQL is not controlled by any corporation or other private entity and the source code is available free of charge. A Brief History of PostgreSQL PostgreSQL, originally called Postgres, was created at UCB by a computer science professor named Michael Stonebraker. Stonebraker started Postgres in 1986 as a follow-up project to its predecessor, Ingres, now owned by Computer Associates. 1977-1985 − A project called INGRES was developed. Proof-of-concept for relational databases Established the company Ingres in 1980 Bought by Computer Associates in 1994 1986-1994 − POSTGRES Development of the concepts in INGRES with a focus on object orientation and the query language – Quel The code base of INGRES was not used as a basis for POSTGRES Commercialized as Illustra (bought by Informix, bought by IBM) 1994-1995 − Postgres95 Support for SQL was added in 1994 Released as Postgres95 in 1995 Re-released as PostgreSQL 6.0 in 1996 Establishment of the PostgreSQL Global Development Team Key Features of PostgreSQL PostgreSQL runs on all major operating systems, including Linux, UNIX (AIX, BSD, HP-UX, SGI IRIX, Mac OS X, Solaris, Tru64), and Windows. It supports text, images, sounds, and video, and includes programming interfaces for C / C++, Java, Perl, Python, Ruby, Tcl and Open Database Connectivity (ODBC). PostgreSQL supports a large part of the SQL standard and offers many modern features including the following − Complex SQL queries SQL Sub-selects Foreign keys Trigger Views Transactions Multiversion concurrency control (MVCC) Streaming Replication (as of 9.0) Hot Standby (as of 9.0) You can check official documentation of PostgreSQL to understand the above-mentioned features. PostgreSQL can be extended by the user in many ways. For example by adding new − Data types Functions Operators Aggregate functions Index methods Procedural Languages Support PostgreSQL supports four standard procedural languages, which allows the users to write their own code in any of the languages and it can be executed by PostgreSQL database server. These procedural languages are – PL/pgSQL, PL/Tcl, PL/Perl and PL/Python. Besides, other non-standard procedural languages like PL/PHP, PL/V8, PL/Ruby, PL/Java, etc., are also supported. PostgreSQL – Environment Setup To start understanding the PostgreSQL basics, first let us install the PostgreSQL. This chapter explains about installing the PostgreSQL on Linux, Windows and Mac OS platforms. Installing PostgreSQL on Linux/Unix Follow the given steps to install PostgreSQL on your Linux machine. Make sure you are logged in as root before you proceed for the installation. Pick the version number of PostgreSQL you want and, as exactly as possible, the platform you want from EnterpriseDB I downloaded postgresql-9.2.4-1-linux-x64.run for my 64 bit CentOS-6 machine. Now, let us execute it as follows − [root@host]# chmod +x postgresql-9.2.4-1-linux-x64.run [root@host]# ./postgresql-9.2.4-1-linux-x64.run ———————————————————————— Welcome to the PostgreSQL Setup Wizard. ———————————————————————— Please specify the directory where PostgreSQL will be installed. Installation Directory [/opt/PostgreSQL/9.2]: Once you launch the installer, it asks you a few basic questions like location of the installation, password of the user who will use database, port number, etc. So keep all of them at their default values except password, which you can provide password as per your choice. It will install PostgreSQL at your Linux machine and will display the following message − Please wait while Setup installs PostgreSQL on your computer. Installing 0% ______________ 50% ______________ 100% ######################################### ———————————————————————– Setup has finished installing PostgreSQL on your computer. Follow the following post-installation steps to create your database − [root@host]# su – postgres Password: bash-4.1$ createdb testdb bash-4.1$ psql testdb psql (8.4.13, server 9.2.4) test=# You can start/restart postgres server in case it is not running using the following command − [root@host]# service postgresql restart Stopping postgresql service: [ OK ] Starting postgresql service: [ OK ] If your installation was correct, you will have PotsgreSQL prompt test=# as shown above. Installing PostgreSQL on Windows Follow the given steps to install PostgreSQL on your Windows machine. Make sure you have turned Third Party Antivirus off while installing. Pick the version number of PostgreSQL you want and, as exactly as possible, the platform you want from EnterpriseDB I downloaded postgresql-9.2.4-1-windows.exe for my Windows PC running in 32bit mode, so let us run postgresql-9.2.4-1-windows.exe as administrator to install PostgreSQL. Select the location where you want to install it. By default, it is installed within Program Files folder. The next step of the installation process would be to select the directory where your data would be stored. By default, it is stored under the “data” directory. Next, the setup asks for password, so you can use your favorite password. The next step; keep the port as default. In the next step, when asked for “Locale”, I selected “English, United States”. It takes a while to install PostgreSQL on your system. On completion of the installation process, you will get the following screen. Uncheck the checkbox and click the Finish button. After the installation process is completed, you can access pgAdmin III, StackBuilder and PostgreSQL shell from your Program Menu under PostgreSQL 9.2. Installing PostgreSQL on Mac Follow the given steps to install PostgreSQL on your Mac machine. Make sure you are logged in as administrator before you proceed for the installation. Pick the latest version number of PostgreSQL for Mac OS available at EnterpriseDB I downloaded postgresql-9.2.4-1-osx.dmg for my Mac OS running with OS X version 10.8.3. Now, let us open the dmg image in finder and just double click it which will give you PostgreSQL installer in the following window − Next, click the postgres-9.2.4-1-osx icon, which will give a warning message. Accept

PostgreSQL – Java

PostgreSQL – JAVA Interface ”; Previous Next Installation Before we start using PostgreSQL in our Java programs, we need to make sure that we have PostgreSQL JDBC and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now let us check how to set up PostgreSQL JDBC driver. Download the latest version of postgresql-(VERSION).jdbc.jar from postgresql-jdbc repository. Add downloaded jar file postgresql-(VERSION).jdbc.jar in your class path, or you can use it along with -classpath option as explained below in the examples. The following section assumes you have little knowledge about Java JDBC concepts. If you do not have, then it is suggested to spent half and hour with JDBC Tutorial to become comfortable with concepts explained below. Connecting To Database The following Java code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned. import java.sql.Connection; import java.sql.DriverManager; public class PostgreSQLJDBC { public static void main(String args[]) { Connection c = null; try { Class.forName(“org.postgresql.Driver”); c = DriverManager .getConnection(“jdbc:postgresql://localhost:5432/testdb”, “postgres”, “123”); } catch (Exception e) { e.printStackTrace(); System.err.println(e.getClass().getName()+”: “+e.getMessage()); System.exit(0); } System.out.println(“Opened database successfully”); } } Before you compile and run above program, find pg_hba.conf file in your PostgreSQL installation directory and add the following line − # IPv4 local connections: host all all 127.0.0.1/32 md5 You can start/restart the postgres server in case it is not running using the following command − [root@host]# service postgresql restart Stopping postgresql service: [ OK ] Starting postgresql service: [ OK ] Now, let us compile and run the above program to connect with testdb. Here, we are using postgres as user ID and 123 as password to access the database. You can change this as per your database configuration and setup. We are also assuming current version of JDBC driver postgresql-9.2-1002.jdbc3.jar is available in the current path. C:JavaPostgresIntegration>javac PostgreSQLJDBC.java C:JavaPostgresIntegration>java -cp c:toolspostgresql-9.2-1002.jdbc3.jar;C:JavaPostgresIntegration PostgreSQLJDBC Open database successfully Create a Table The following Java program will be used to create a table in previously opened database. Make sure you do not have this table already in your target database. import java.sql.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class PostgreSQLJDBC { public static void main( String args[] ) { Connection c = null; Statement stmt = null; try { Class.forName(“org.postgresql.Driver”); c = DriverManager .getConnection(“jdbc:postgresql://localhost:5432/testdb”, “manisha”, “123”); System.out.println(“Opened database successfully”); stmt = c.createStatement(); String sql = “CREATE TABLE COMPANY ” + “(ID INT PRIMARY KEY NOT NULL,” + ” NAME TEXT NOT NULL, ” + ” AGE INT NOT NULL, ” + ” ADDRESS CHAR(50), ” + ” SALARY REAL)”; stmt.executeUpdate(sql); stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName()+”: “+ e.getMessage() ); System.exit(0); } System.out.println(“Table created successfully”); } } When a program is compiled and executed, it will create the COMPANY table in testdb database and will display the following two lines − Opened database successfully Table created successfully INSERT Operation The following Java program shows how we can create records in our COMPANY table created in above example − import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class PostgreSQLJDBC { public static void main(String args[]) { Connection c = null; Statement stmt = null; try { Class.forName(“org.postgresql.Driver”); c = DriverManager .getConnection(“jdbc:postgresql://localhost:5432/testdb”, “manisha”, “123”); c.setAutoCommit(false); System.out.println(“Opened database successfully”); stmt = c.createStatement(); String sql = “INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) ” + “VALUES (1, ”Paul”, 32, ”California”, 20000.00 );”; stmt.executeUpdate(sql); sql = “INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) ” + “VALUES (2, ”Allen”, 25, ”Texas”, 15000.00 );”; stmt.executeUpdate(sql); sql = “INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) ” + “VALUES (3, ”Teddy”, 23, ”Norway”, 20000.00 );”; stmt.executeUpdate(sql); sql = “INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) ” + “VALUES (4, ”Mark”, 25, ”Rich-Mond ”, 65000.00 );”; stmt.executeUpdate(sql); stmt.close(); c.commit(); c.close(); } catch (Exception e) { System.err.println( e.getClass().getName()+”: “+ e.getMessage() ); System.exit(0); } System.out.println(“Records created successfully”); } } When the above program is compiled and executed, it will create given records in COMPANY table and will display the following two lines − Opened database successfully Records created successfully SELECT Operation The following Java program shows how we can fetch and display records from our COMPANY table created in above example − import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class PostgreSQLJDBC { public static void main( String args[] ) { Connection c = null; Statement stmt = null; try { Class.forName(“org.postgresql.Driver”); c = DriverManager .getConnection(“jdbc:postgresql://localhost:5432/testdb”, “manisha”, “123”); c.setAutoCommit(false); System.out.println(“Opened database successfully”); stmt = c.createStatement(); ResultSet rs = stmt.executeQuery( “SELECT * FROM COMPANY;” ); while ( rs.next() ) { int id = rs.getInt(“id”); String name = rs.getString(“name”); int age = rs.getInt(“age”); String address = rs.getString(“address”); float salary = rs.getFloat(“salary”); System.out.println( “ID = ” + id ); System.out.println( “NAME = ” + name ); System.out.println( “AGE = ” + age ); System.out.println( “ADDRESS = ” + address ); System.out.println( “SALARY = ” + salary ); System.out.println(); } rs.close(); stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName()+”: “+ e.getMessage() ); System.exit(0); } System.out.println(“Operation done successfully”); } } When the program is compiled and executed, it will produce the following result − Opened database successfully ID = 1 NAME = Paul AGE = 32 ADDRESS = California SALARY = 20000.0 ID = 2 NAME = Allen AGE = 25 ADDRESS = Texas SALARY = 15000.0 ID = 3 NAME = Teddy AGE = 23 ADDRESS = Norway SALARY = 20000.0 ID = 4 NAME = Mark AGE = 25 ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully UPDATE Operation The following Java code shows how we can use the UPDATE statement to update any record and then fetch and display updated records from our COMPANY table − import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class PostgreSQLJDBC { public static void main( String args[] ) { Connection c = null; Statement stmt = null; try { Class.forName(“org.postgresql.Driver”); c = DriverManager .getConnection(“jdbc:postgresql://localhost:5432/testdb”, “manisha”, “123”); c.setAutoCommit(false); System.out.println(“Opened database successfully”); stmt = c.createStatement(); String sql = “UPDATE COMPANY set SALARY = 25000.00 where ID=1;”; stmt.executeUpdate(sql); c.commit();

PostgreSQL – Discussion

Discuss PostgreSQL ”; Previous Next PostgreSQL is a powerful, open source object-relational database system. It has more than 15 years of active development and a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness. PostgreSQL runs on all major operating systems, including Linux, UNIX (AIX, BSD, HP-UX, SGI IRIX, Mac OS X, Solaris, Tru64), and Windows. This tutorial will give you quick start with PostgreSQL and make you comfortable with PostgreSQL programming. Print Page Previous Next Advertisements ”;

PostgreSQL – Useful Functions

PostgreSQL – Useful Functions ”; Previous Next PostgreSQL built-in functions, also called as Aggregate functions, are used for performing processing on string or numeric data. The following is the list of all general-purpose PostgreSQL built-in functions − PostgreSQL COUNT Function − The PostgreSQL COUNT aggregate function is used to count the number of rows in a database table. PostgreSQL MAX Function − The PostgreSQL MAX aggregate function allows us to select the highest (maximum) value for a certain column. PostgreSQL MIN Function − The PostgreSQL MIN aggregate function allows us to select the lowest (minimum) value for a certain column. PostgreSQL AVG Function − The PostgreSQL AVG aggregate function selects the average value for certain table column. PostgreSQL SUM Function − The PostgreSQL SUM aggregate function allows selecting the total for a numeric column. PostgreSQL ARRAY Functions − The PostgreSQL ARRAY aggregate function puts input values, including nulls, concatenated into an array. PostgreSQL Numeric Functions − Complete list of PostgreSQL functions required to manipulate numbers in SQL. PostgreSQL String Functions − Complete list of PostgreSQL functions required to manipulate strings in PostgreSQL. Print Page Previous Next Advertisements ”;

PostgreSQL – Python

PostgreSQL – Python Interface ”; Previous Next Installation The PostgreSQL can be integrated with Python using psycopg2 module. sycopg2 is a PostgreSQL database adapter for the Python programming language. psycopg2 was written with the aim of being very small and fast, and stable as a rock. You do not need to install this module separately because it is shipped, by default, along with Python version 2.5.x onwards. If you do not have it installed on your machine then you can use yum command to install it as follows − $yum install python-psycopg2 To use psycopg2 module, you must first create a Connection object that represents the database and then optionally you can create cursor object which will help you in executing all the SQL statements. Python psycopg2 module APIs The following are important psycopg2 module routines, which can suffice your requirement to work with PostgreSQL database from your Python program. If you are looking for a more sophisticated application, then you can look into Python psycopg2 module”s official documentation. S. No. API & Description 1 psycopg2.connect(database=”testdb”, user=”postgres”, password=”cohondob”, host=”127.0.0.1″, port=”5432″) This API opens a connection to the PostgreSQL database. If database is opened successfully, it returns a connection object. 2 connection.cursor() This routine creates a cursor which will be used throughout of your database programming with Python. 3 cursor.execute(sql [, optional parameters]) This routine executes an SQL statement. The SQL statement may be parameterized (i.e., placeholders instead of SQL literals). The psycopg2 module supports placeholder using %s sign For example:cursor.execute(“insert into people values (%s, %s)”, (who, age)) 4 cursor.executemany(sql, seq_of_parameters) This routine executes an SQL command against all parameter sequences or mappings found in the sequence sql. 5 cursor.callproc(procname[, parameters]) This routine executes a stored database procedure with the given name. The sequence of parameters must contain one entry for each argument that the procedure expects. 6 cursor.rowcount This read-only attribute which returns the total number of database rows that have been modified, inserted, or deleted by the last last execute*(). 7 connection.commit() This method commits the current transaction. If you do not call this method, anything you did since the last call to commit() is not visible from other database connections. 8 connection.rollback() This method rolls back any changes to the database since the last call to commit(). 9 connection.close() This method closes the database connection. Note that this does not automatically call commit(). If you just close your database connection without calling commit() first, your changes will be lost! 10 cursor.fetchone() This method fetches the next row of a query result set, returning a single sequence, or None when no more data is available. 11 cursor.fetchmany([size=cursor.arraysize]) This routine fetches the next set of rows of a query result, returning a list. An empty list is returned when no more rows are available. The method tries to fetch as many rows as indicated by the size parameter. 12 cursor.fetchall() This routine fetches all (remaining) rows of a query result, returning a list. An empty list is returned when no rows are available. Connecting to Database The following Python code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned. #!/usr/bin/python import psycopg2 conn = psycopg2.connect(database=”testdb”, user = “postgres”, password = “pass123”, host = “127.0.0.1”, port = “5432”) print “Opened database successfully” Here, you can also supply database testdb as name and if database is successfully opened, then it will give the following message − Open database successfully Create a Table The following Python program will be used to create a table in previously created database − #!/usr/bin/python import psycopg2 conn = psycopg2.connect(database = “testdb”, user = “postgres”, password = “pass123”, host = “127.0.0.1”, port = “5432”) print “Opened database successfully” cur = conn.cursor() cur.execute(”””CREATE TABLE COMPANY (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL);”””) print “Table created successfully” conn.commit() conn.close() When the above given program is executed, it will create COMPANY table in your test.db and it will display the following messages − Opened database successfully Table created successfully INSERT Operation The following Python program shows how we can create records in our COMPANY table created in the above example − #!/usr/bin/python import psycopg2 conn = psycopg2.connect(database = “testdb”, user = “postgres”, password = “pass123”, host = “127.0.0.1”, port = “5432”) print “Opened database successfully” cur = conn.cursor() cur.execute(“INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, ”Paul”, 32, ”California”, 20000.00 )”); cur.execute(“INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, ”Allen”, 25, ”Texas”, 15000.00 )”); cur.execute(“INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, ”Teddy”, 23, ”Norway”, 20000.00 )”); cur.execute(“INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, ”Mark”, 25, ”Rich-Mond ”, 65000.00 )”); conn.commit() print “Records created successfully”; conn.close() When the above given program is executed, it will create given records in COMPANY table and will display the following two lines − Opened database successfully Records created successfully SELECT Operation The following Python program shows how we can fetch and display records from our COMPANY table created in the above example − #!/usr/bin/python import psycopg2 conn = psycopg2.connect(database = “testdb”, user = “postgres”, password = “pass123”, host = “127.0.0.1”, port = “5432”) print “Opened database successfully” cur = conn.cursor() cur.execute(“SELECT id, name, address, salary from COMPANY”) rows = cur.fetchall() for row in rows: print “ID = “, row[0] print “NAME = “, row[1] print “ADDRESS = “, row[2] print “SALARY = “, row[3], “n” print “Operation done successfully”; conn.close() When the above given program is executed, it will produce the following result − Opened database successfully ID = 1 NAME = Paul ADDRESS = California SALARY = 20000.0 ID = 2 NAME = Allen ADDRESS = Texas SALARY = 15000.0 ID = 3 NAME = Teddy ADDRESS = Norway SALARY = 20000.0 ID = 4 NAME = Mark ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully UPDATE Operation The following Python code shows how we can use the UPDATE statement to update any record and then fetch

PostgreSQL – C/C++

PostgreSQL – C/C++ Interface ”; Previous Next This tutorial is going to use libpqxx library, which is the official C++ client API for PostgreSQL. The source code for libpqxx is available under the BSD license, so you are free to download it, pass it on to others, change it, sell it, include it in your own code, and share your changes with anyone you choose. Installation The the latest version of libpqxx is available to be downloaded from the link Download Libpqxx. So download the latest version and follow the following steps − wget http://pqxx.org/download/software/libpqxx/libpqxx-4.0.tar.gz tar xvfz libpqxx-4.0.tar.gz cd libpqxx-4.0 ./configure make make install Before you start using C/C++ PostgreSQL interface, find the pg_hba.conf file in your PostgreSQL installation directory and add the following line − # IPv4 local connections: host all all 127.0.0.1/32 md5 You can start/restart postgres server in case it is not running using the following command − [root@host]# service postgresql restart Stopping postgresql service: [ OK ] Starting postgresql service: [ OK ] C/C++ Interface APIs The following are important interface routines which can sufice your requirement to work with PostgreSQL database from your C/C++ program. If you are looking for a more sophisticated application then you can look into the libpqxx official documentation, or you can use commercially available APIs. S. No. API & Description 1 pqxx::connection C( const std::string & dbstring ) This is a typedef which will be used to connect to the database. Here, dbstring provides required parameters to connect to the datbase, for example dbname = testdb user = postgres password=pass123 hostaddr=127.0.0.1 port=5432. If connection is setup successfully then it creates C with connection object which provides various useful function public function. 2 C.is_open() The method is_open() is a public method of connection object and returns boolean value. If connection is active, then this method returns true otherwise it returns false. 3 C.disconnect() This method is used to disconnect an opened database connection. 4 pqxx::work W( C ) This is a typedef which will be used to create a transactional object using connection C, which ultimately will be used to execute SQL statements in transactional mode. If transaction object gets created successfully, then it is assigned to variable W which will be used to access public methods related to transactional object. 5 W.exec(const std::string & sql) This public method from transactional object will be used to execute SQL statement. 6 W.commit() This public method from transactional object will be used to commit the transaction. 7 W.abort() This public method from transactional object will be used to rollback the transaction. 8 pqxx::nontransaction N( C ) This is a typedef which will be used to create a non-transactional object using connection C, which ultimately will be used to execute SQL statements in non-transactional mode. If transaction object gets created successfully, then it is assigned to variable N which will be used to access public methods related to non-transactional object. 9 N.exec(const std::string & sql) This public method from non-transactional object will be used to execute SQL statement and returns a result object which is actually an interator holding all the returned records. Connecting To Database The following C code segment shows how to connect to an existing database running on local machine at port 5432. Here, I used backslash for line continuation. #include <iostream> #include <pqxx/pqxx> using namespace std; using namespace pqxx; int main(int argc, char* argv[]) { try { connection C(“dbname = testdb user = postgres password = cohondob hostaddr = 127.0.0.1 port = 5432”); if (C.is_open()) { cout << “Opened database successfully: ” << C.dbname() << endl; } else { cout << “Can”t open database” << endl; return 1; } C.disconnect (); } catch (const std::exception &e) { cerr << e.what() << std::endl; return 1; } } Now, let us compile and run the above program to connect to our database testdb, which is already available in your schema and can be accessed using user postgres and password pass123. You can use the user ID and password based on your database setting. Remember to keep the -lpqxx and -lpq in the given order! Otherwise, the linker will complain bitterly about the missing functions with names starting with “PQ.” $g++ test.cpp -lpqxx -lpq $./a.out Opened database successfully: testdb Create a Table The following C code segment will be used to create a table in previously created database − #include <iostream> #include <pqxx/pqxx> using namespace std; using namespace pqxx; int main(int argc, char* argv[]) { char * sql; try { connection C(“dbname = testdb user = postgres password = cohondob hostaddr = 127.0.0.1 port = 5432”); if (C.is_open()) { cout << “Opened database successfully: ” << C.dbname() << endl; } else { cout << “Can”t open database” << endl; return 1; } /* Create SQL statement */ sql = “CREATE TABLE COMPANY(” “ID INT PRIMARY KEY NOT NULL,” “NAME TEXT NOT NULL,” “AGE INT NOT NULL,” “ADDRESS CHAR(50),” “SALARY REAL );”; /* Create a transactional object. */ work W(C); /* Execute SQL query */ W.exec( sql ); W.commit(); cout << “Table created successfully” << endl; C.disconnect (); } catch (const std::exception &e) { cerr << e.what() << std::endl; return 1; } return 0; } When the above given program is compiled and executed, it will create COMPANY table in your testdb database and will display the following statements − Opened database successfully: testdb Table created successfully INSERT Operation The following C code segment shows how we can create records in our COMPANY table created in above example − #include <iostream> #include <pqxx/pqxx> using namespace std; using namespace pqxx; int main(int argc, char* argv[]) { char * sql; try { connection C(“dbname = testdb user = postgres password = cohondob hostaddr = 127.0.0.1 port = 5432”); if (C.is_open()) { cout << “Opened database successfully: ” << C.dbname() << endl; } else { cout << “Can”t open database” << endl; return 1; } /* Create SQL statement */ sql = “INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) ” “VALUES (1, ”Paul”, 32, ”California”, 20000.00

PostgreSQL – Functions

PostgreSQL – Functions ”; Previous Next PostgreSQL functions, also known as Stored Procedures, allow you to carry out operations that would normally take several queries and round trips in a single function within the database. Functions allow database reuse as other applications can interact directly with your stored procedures instead of a middle-tier or duplicating code. Functions can be created in a language of your choice like SQL, PL/pgSQL, C, Python, etc. Syntax The basic syntax to create a function is as follows − CREATE [OR REPLACE] FUNCTION function_name (arguments) RETURNS return_datatype AS $variable_name$ DECLARE declaration; […] BEGIN < function_body > […] RETURN { variable_name | value } END; LANGUAGE plpgsql; Where, function-name specifies the name of the function. [OR REPLACE] option allows modifying an existing function. The function must contain a return statement. RETURN clause specifies that data type you are going to return from the function. The return_datatype can be a base, composite, or domain type, or can reference the type of a table column. function-body contains the executable part. The AS keyword is used for creating a standalone function. plpgsql is the name of the language that the function is implemented in. Here, we use this option for PostgreSQL, it Can be SQL, C, internal, or the name of a user-defined procedural language. For backward compatibility, the name can be enclosed by single quotes. Example The following example illustrates creating and calling a standalone function. This function returns the total number of records in the COMPANY table. We will use the COMPANY table, which has the following records − testdb# select * from COMPANY; id | name | age | address | salary —-+——-+—–+———–+——– 1 | Paul | 32 | California| 20000 2 | Allen | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall| 45000 7 | James | 24 | Houston | 10000 (7 rows) Function totalRecords() is as follows − CREATE OR REPLACE FUNCTION totalRecords () RETURNS integer AS $total$ declare total integer; BEGIN SELECT count(*) into total FROM COMPANY; RETURN total; END; $total$ LANGUAGE plpgsql; When the above query is executed, the result would be − testdb# CREATE FUNCTION Now, let us execute a call to this function and check the records in the COMPANY table testdb=# select totalRecords(); When the above query is executed, the result would be − totalrecords ————– 7 (1 row) Print Page Previous Next Advertisements ”;

PostgreSQL – Views

PostgreSQL – VIEWS ”; Previous Next Views are pseudo-tables. That is, they are not real tables; nevertheless appear as ordinary tables to SELECT. A view can represent a subset of a real table, selecting certain columns or certain rows from an ordinary table. A view can even represent joined tables. Because views are assigned separate permissions, you can use them to restrict table access so that the users see only specific rows or columns of a table. A view can contain all rows of a table or selected rows from one or more tables. A view can be created from one or many tables, which depends on the written PostgreSQL query to create a view. Views, which are kind of virtual tables, allow users to do the following − Structure data in a way that users or classes of users find natural or intuitive. Restrict access to the data such that a user can only see limited data instead of complete table. Summarize data from various tables, which can be used to generate reports. Since views are not ordinary tables, you may not be able to execute a DELETE, INSERT, or UPDATE statement on a view. However, you can create a RULE to correct this problem of using DELETE, INSERT or UPDATE on a view. Creating Views The PostgreSQL views are created using the CREATE VIEW statement. The PostgreSQL views can be created from a single table, multiple tables, or another view. The basic CREATE VIEW syntax is as follows − CREATE [TEMP | TEMPORARY] VIEW view_name AS SELECT column1, column2….. FROM table_name WHERE [condition]; You can include multiple tables in your SELECT statement in very similar way as you use them in normal PostgreSQL SELECT query. If the optional TEMP or TEMPORARY keyword is present, the view will be created in the temporary space. Temporary views are automatically dropped at the end of the current session. Example Consider, the COMPANY table is having the following records − id | name | age | address | salary —-+——-+—–+————+——– 1 | Paul | 32 | California | 20000 2 | Allen | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall | 45000 7 | James | 24 | Houston | 10000 Now, following is an example to create a view from COMPANY table. This view would be used to have only few columns from COMPANY table − testdb=# CREATE VIEW COMPANY_VIEW AS SELECT ID, NAME, AGE FROM COMPANY; Now, you can query COMPANY_VIEW in a similar way as you query an actual table. Following is the example − testdb=# SELECT * FROM COMPANY_VIEW; This would produce the following result − id | name | age —-+——-+—– 1 | Paul | 32 2 | Allen | 25 3 | Teddy | 23 4 | Mark | 25 5 | David | 27 6 | Kim | 22 7 | James | 24 (7 rows) Dropping Views To drop a view, simply use the DROP VIEW statement with the view_name. The basic DROP VIEW syntax is as follows − testdb=# DROP VIEW view_name; The following command will delete COMPANY_VIEW view, which we created in the last section − testdb=# DROP VIEW COMPANY_VIEW; Print Page Previous Next Advertisements ”;