Use C Language to Connect postgreSQL
There is a small example copied from postgreSQL.org
1 |
|
above is how to connect localhost database. If you want to connect with remote postgreSQL server. You will following those rules(copied from vivek):
Step # 1: Login over ssh if server is outside your IDC
1 | $ ssh [email protected] |
Step # 2: Enable client authentication
Once connected, you need edit the PostgreSQL configuration file, edit the PostgreSQL configuration file /var/lib/pgsql/data/pg_hba.conf (or /etc/postgresql/8.2/main/pg_hba.conf for latest 8.2 version) using a text editor such as vi.
Login as postgres user using su / sudo command, enter:
1 | $ su - postgres |
Save and close the file. Make sure you replace 10.10.29.0/24 with actual network IP address range of the clients system in your own network.
Step # 3: Enable networking for PostgreSQL
You need to enable TCP / IP networking. Use either step #3 or #3a as per your PostgreSQL database server version.
Step # 4: Allow TCP/IP socket
If you are using PostgreSQL version 8.x or newer use the following instructions or skip to Step # 3a for older version (7.x or older).
You need to open PostgreSQL configuration file /var/lib/pgsql/data/postgresql.conf or /etc/postgresql/8.2/main/postgresql.conf.
1 | # vi /etc/postgresql/8.2/main/postgresql.conf |
Save and close the file. Skip to step # 4.
Step #4a - Information for old version 7.x or older
Following configuration only required for PostgreSQL version 7.x or older. Open config file, enter:
1 | # vi /var/lib/pgsql/data/postgresql.conf |
Save and close the file.
Step # 5: Restart PostgreSQL Server
Type the following command:
1 | # /etc/init.d/postgresql restart |
Step # 6: Iptables firewall rules
Make sure iptables is not blocking communication, open port 5432 (append rules to your iptables scripts or file /etc/sysconfig/iptables):
1 | iptables -A INPUT -p tcp -s 0/0 --sport 1024:65535 -d 10.10.29.50 --dport 5432\ |
Step # 7: Test your setup
Use psql command from client system. Connect to remote server using IP address 10.10.29.50 and login using vivek username and sales database, enter:
1 | $ psql -h 10.10.29.50 -U vivek -d sales |
Step #8: Change your code
1 | const char * connstr = "host='10.10.29.50' dbname='my_database' user='postgres' password='secret'" |