Home > database >  How to export database as sql in asp net core web api from client side
How to export database as sql in asp net core web api from client side

Time:12-23

I am using Asp.Net Core Web API and PostgreSQL for the database. How can the admins take the database backup as .sql file and can restore the data back whenever they want. I have nine tables.

CodePudding user response:

You can use pg_dump. Your C# code may look like below:

var process = new Process();
var startInfo = new ProcessStartInfo();
startInfo.FileName = Path.Combine("PostgreSQL", "postgresql-backup.bat");
var host = "For Example:localhost";
var port = "For Example:5432";
var user = "For Example:postgres";
var database = "Your databaseName";
var outputPath = "Your localDatabasePath";

// use pg_dump, specifying the host, port, user, database to back up, and the output path.
// the host, port, user, and database must be an exact match with what's inside your pgpass.conf (Windows)
startInfo.Arguments = $@"{host} {port} {user} {database} ""{outputPath}""";
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
process.Close();

Restoring a database is similar, but using pg_restore.

For more details, you can refer to this GitHub.

Hope this can help you.

  • Related