If your data is stored in a PostgreSQL table, you can prevent mishaps by regularly backing up your databases. This document shows you the built-in commands that simplify the process.

Ever accidentally deleted a database table, or had the disk with your live database crash? If so, you know all too well that sinking feeling you get when you realize that weeks of hard work just vanished into nothingness.

Well, it doesn't always have to be that way. If your data is stored in a PostgreSQL table, you can prevent mishaps by regularly backing up your databases. PostgreSQL comes with built-in tools to perform such back ups and, in the event of a system crash or accident, the tools allow you to "roll back" and restore the system to its original state from a previously-saved snapshot.

Backing up data
PostgreSQL comes with a built-in backup tool called pg_dump. The tool works by reading the selected database and reproducing its contents as a series of SQL commands, which serve as a snapshot and can be used to recreate the data at a later date. A client-server connection is used to perform backups.

Note: Before proceeding, ensure that you have the credentials needed to log in to the server and read the database or table you wish to back up. You can do this by using the PostgreSQL command-line client, psql, to attempt a server login. Pass the host name (-h), user name (-u) and password (-p), and database name to the client, and check whether you are granted access.

Using pg_dump is simplicity itselfââ,¬"just run the program at the command prompt with the name of the database to be exported, as below (alter the path to your PostgreSQL installation as needed):

$ /usr/local/pgsql/bin/pg_dump -D -h localhost -U pgsql test > test.bak

This will create the file test.bak and populate it with the SQL commands needed to regenerate the database. Look inside the file, and you will see something like this next example:

--
-- Name: pets; Type: TABLE; Schema: public; Owner: root; Tablespace:
--

CREATE TABLE pets (
Ã, Ã, Ã,  species character varying,
Ã, Ã, Ã,  name character varying
);

ALTER TABLE public.pets OWNER TO root;

--
-- Data for Name: pets; Type: TABLE DATA; Schema: public; Owner: root
--

INSERT INTO pets (species, name) VALUES ('dog', 'Sparky');
INSERT INTO pets (species, name) VALUES ('cat', 'Tabitha');

If you would prefer to back up all the databases on the system (rather than just one), you can use the pg_dumpall command instead of pg_dump. This command backs up all the databases PostgreSQL knows about (including its own system databases) to a single file. Here's an example of how to use it:

$ /usr/local/pgsql/bin/pg_dumpall -D -h localhost -U pgsql > all.bak

To ensure that your backups are always fresh, you should schedule a recurring backup, by adding the pg_dump or pg_dumpall command to your cron table. Here are two example cron entries. The first one backs up the test database every night at 3 AM, and the second backs up all the databases once a week, on Fridays at 9 PM:

0 3 * * * Ã,  /usr/local/pgsql/bin/pg_dump -D -h localhost -U pgsql test > /disk2/test.bak0 21 * * 5 /usr/local/pgsql/bin/pg_dumpall -D -h localhost -U pgsql > /disk2/all.bak

Restoring data

Restoring data from a backup is even simpler than creating the backupââ,¬"all you need do is recreate the databases by executing the SQL commands in the backup file.

If you backed up a single database with pg_dump, the backup will contain CREATE TABLE statements to reproduce the original tables. However, it is necessary for you to first generate an empty database to store these tables. This is easily done with a call to the createdb tool, also part of the PostgreSQL suite:

$ /usr/local/pgsql/bin/createdb restored

You can now restore the database by executing the SQL commands in the backup file:

$ /usr/local/pgsql/bin/psql -h localhost -U pgsql -d restored < test.bak

If you backed up all the databases with pg_dumpall, there is no requirement to first create databases, because the backup file will contain the necessary calls to CREATE DATABASE. In this case, simply pipe the backup file through the psql command-line client without specifying a target database:

$ /usr/local/pgsql/bin/psql -h localhost -U pgsql < all.bak

Once the data recovery is complete, you should be able to log in to the server and see your restored data.

Do you need help with MySQL? Gain advice from Builder AU forums

Related links

Comments

1

Satya Narayan - 26/02/08

Pass the host name (-h), user name (-u) and password (-p), and database name to the client,

I am sure this line sounds something wrong, please correct it like,
-h (hostname) -p (port number) -U (username), -W(password),
and here all options are case-sensitive.

C:\Program Files\PostgreSQL\8.3\bin>pg_dump -C -h localhost -p 5432 -U postgres test > test.bak   (path to your postgres installtion directory)

» Report offensive content

2

Harvinder - 16/09/08

I am developing a C# application and could not find any details on backing up the database using C#. I would like to provide the users of the application ability to save a backup of the database in case of any data lose or any other type of failures such as Hard disk failure and so on.

I would really appreciate if someone could provide information on this issue. The specification of the system I am using is:

OS: Windows XP Pro/Windows Vista
DB: PostgreSQL
.Net Connection for C#: Npgsql

I would really appreciate if someone could help please, and also an example in C# would be brilliant as I am kind of new in C#, my background is mainly from Java.

Thanks in advance and I look for a solution.

» Report offensive content

3

prabhakar - 17/09/08

Hi..this will work

string strshp, pathshp;
private void button1_Click(object sender, EventArgs e)
{
try
{

string user = txtExistDBName.Text;
string user1 = textBox1.Text;
// string Creten = "/c pg_dump -h 127.0.0.1 -U postgres -d" + " " + user + " " + "> gdm";

string Creten = "/c pg_dump -h 127.0.0.1 -U postgres -d" + " " + user + " " + "> " + " " + user1 + " " + "";

ProcessStartInfo Pinfo = new ProcessStartInfo("cmd.exe", Creten);


Pinfo.RedirectStandardError = false;
Pinfo.UseShellExecute = false;
string Output = string.Empty;

Process p = new Process();

p.StartInfo = Pinfo;
p.StartInfo.CreateNoWindow = false;
p.Start();
while (!p.HasExited)
System.Threading.Thread.Sleep(1000);
p.WaitForExit();
p.Close();



}

» Report offensive content

4

Masaddy - 19/03/09

Mr Prahabkar

can you send me your program,how i can backup and restore postgres database using C#

thanks.
masaddy@gmail.com

» Report offensive content

Leave a comment

You must read and type the 6 chars within 0..9 and A..F

* indicates mandatory fields.

4

Masaddy - 19/03/09

Mr Prahabkar can you send me your program,how i can backup and restore postgres database using C# thanks. masaddy@gmail.com ... more

3

prabhakar - 17/09/08

Hi..this will work string strshp, pathshp; private void button1_Click(object sender, EventArgs e) ... more

2

Harvinder - 16/09/08

I am developing a C# application and could not find any details on backing up the database using C#. I would ... more

Log in


Sign up | Forgot your password?

  • Staff Aussies to pay more for Win 7

    If you are looking to make some money in these troubled times, perhaps importing copies of Windows 7 could be for you. Read more »

    -- posted by Staff

  • Staff Firefox: Greens want it, 3.5rc2 not up to par

    This week's roundup looks at the situation surrounding a campaign to change Outlook HTML renderer, a Greens MP wants to install Firefox but is restricted and all the photos from the iPhone 3GS launch. Read more »

    -- posted by Staff

  • Chris Duckett Microsoft misses the Outlook point

    Ask designers which mail program is the bane of their existence, and you'll find that Outlook tops the list. The reason why the most popular email reader is also the most painful is simple: it uses Word to render HTML emails. Read more »

    -- posted by Chris Duckett

What's on?