我尝试了this方法,但它没有用,任何人都可以纠正它或分享Backup/Restore PostgreSQL using VB.NET
的一些教程
这些方法用于备份/恢复
这里commandType = pg_dump
和commandSentence = -i -h localhost -p 5432 -U postgres -F c -b -v -f C:\Documents and Settings\GDS\Desktop\backup\RStar.backup RStar
但在我尝试放置备份文件的文件夹中没有返回任何内容
private void executeCommand(string commandType,string commandSentence )
{
try
{
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
info.FileName = "C:\\Program Files\\PostgreSQL\\9.2\\bin\\" + commandType + ".exe ";
info.Arguments = commandSentence;
info.CreateNoWindow = true ;
info.UseShellExecute = false;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = info;
proc.Start();
proc.WaitForExit();
if (commandType == "pg_dump")
toolStripStatusLabel1.Text = "Backup successfuly created";
else if (commandType == "pg_restore")
toolStripStatusLabel1.Text = "Restore successfuly executed";
else if(commandType=="shp2pgsql")
toolStripStatusLabel1.Text = "Your selected shape file successfuly transfered to PostGIS";
else if (commandType == "pgsql2shp")
toolStripStatusLabel1.Text = "Your selected layer from PostGIS successfuly converted to shape file";
}
catch (Exception ex)
{
toolStripStatusLabel1.Text = ex.ToString();
}
}
答案 0 :(得分:1)
转储方法(其中pgDumpPath是pg_dump.exe的路径,outFile是输出文件路径):
public void PostgreSqlDump(
string pgDumpPath,
string outFile,
string host,
string port,
string database,
string user,
string password)
{
String dumpCommand = "\"" + pgDumpPath + "\"" + " -Fc" + " -h " + host + " -p " + port + " -d " + database + " -U " + user + "";
String passFileContent = "" + host + ":" + port + ":" + database + ":" + user + ":" + password + "";
String batFilePath = Path.Combine(
Path.GetTempPath(),
Guid.NewGuid().ToString() + ".bat");
String passFilePath = Path.Combine(
Path.GetTempPath(),
Guid.NewGuid().ToString() + ".conf");
try
{
String batchContent = "";
batchContent += "@" + "set PGPASSFILE=" + passFilePath + "\n";
batchContent += "@" + dumpCommand + " > " + "\"" + outFile + "\"" + "\n";
File.WriteAllText(
batFilePath,
batchContent,
Encoding.ASCII);
File.WriteAllText(
passFilePath,
passFileContent,
Encoding.ASCII);
if (File.Exists(outFile))
File.Delete(outFile);
ProcessStartInfo oInfo = new ProcessStartInfo(batFilePath);
oInfo.UseShellExecute = false;
oInfo.CreateNoWindow = true;
using (Process proc = System.Diagnostics.Process.Start(oInfo))
{
proc.WaitForExit();
proc.Close();
}
}
finally
{
if (File.Exists(batFilePath))
File.Delete(batFilePath);
if (File.Exists(passFilePath))
File.Delete(passFilePath);
}
}
答案 1 :(得分:0)
public void Backup()
{
try
{
DateTime Time = DateTime.Now;
int year = Time.Year;
int month = Time.Month;
int day = Time.Day;
int hour = Time.Hour;
int minute = Time.Minute;
int second = Time.Second;
int millisecond = Time.Millisecond;
//Save file to C:\ with the current date as a filename
string path;
path = "D:\\" + year + "-" + month + "-" + day + "-" + hour + "-" + minute + ".sql";
StreamWriter file = new StreamWriter(path);
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "mysqldump";
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true;
psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}", uid, password, server, database);
psi.UseShellExecute = false;
Process process = Process.Start(path);
string output;
output = process.StandardOutput.ReadToEnd();
file.WriteLine(output);
process.WaitForExit();
file.Close();
process.Close();
}
catch (IOException ex)
{
MessageBox.Show("Error , unable to backup!");
}
}
答案 2 :(得分:0)
public void { BackupDatabase(server,port, user,password, dbname, "backupdir", dbname, "C:\\Program Files\\PostgreSQL\\11\\bin\\");
}
public static string BackupDatabase(
string server,
string port,
string user,
string password,
string dbname,
string backupdir,
string backupFileName,
string backupCommandDir)
{
try
{
Environment.SetEnvironmentVariable("PGPASSWORD", password);
string backupFile = backupdir + backupFileName + "_"+DateTime.Now.ToString("yyyy") + "_" + DateTime.Now.ToString("MM") + "_" + DateTime.Now.ToString("dd") + ".backup";
string BackupString = " -f \"" + backupFile + "\" -F c"+
" -h " + server + " -U " + user + " -p " + port + " -d " + dbname;
Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = backupCommandDir + "\\pg_dump.exe";
proc.StartInfo.Arguments = BackupString;
proc.StartInfo.RedirectStandardOutput = true;//for error checks BackupString
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;//use for not opening cmd screen
proc.StartInfo.CreateNoWindow = true;//use for not opening cmd screen
proc.Start();
proc.WaitForExit();
proc.Close();
return backupFile;
}
catch (Exception ex)
{
return null;
}
https://sagartajpara.blogspot.com/2017/03/postgres-database-backup-in-c.html
答案 3 :(得分:0)
只是增强字节响应并与Net Core 3.1 Linux和Windows System一起使用
您可以使用PGPASSWORD而不是PGPASSFILE,因此可以省略为凭证创建中间文件的步骤。
对于Linux,您需要考虑如何使用Process在linux中运行sh脚本: Shell Script File(.sh) does not run from c# core on linux
要在linux中设置变量,应使用export而不是set。
这是我在Linux和Windows OS系统(Net Core 3.1)中还原数据库的示例:
<p id="main">nothing yet!</p>
执行方法
string Set = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "set " : "export ";
public async Task PostgreSqlRestore(
string inputFile,
string host,
string port,
string database,
string user,
string password)
{
string dumpCommand = $"{Set}PGPASSWORD={password}\n" +
$"psql -h {host} -p {port} -U {user} -d {database} -c \"select pg_terminate_backend(pid) from pg_stat_activity where datname = '{database}'\"\n" +
$"dropdb -h " + host + " -p " + port + " -U " + user + $" {database}\n" +
$"createdb -h " + host + " -p " + port + " -U " + user + $" {database}\n" +
"pg_restore -h " + host + " -p " + port + " -d " + database + " -U " + user + "";
//psql command disconnect database
//dropdb and createdb remove database and create.
//pg_restore restore database with file create with pg_dump command
dumpCommand = $"{dumpCommand} {inputFile}";
await Execute(dumpCommand);
}
ProcessInfoByOS方法
private Task Execute(string dumpCommand)
{
return Task.Run(() =>
{
string batFilePath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}." + (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "bat" : "sh"));
try
{
string batchContent = "";
batchContent += $"{dumpCommand}";
File.WriteAllText(batFilePath, batchContent, Encoding.ASCII);
ProcessStartInfo info = ProcessInfoByOS(batFilePath);
using System.Diagnostics.Process proc = System.Diagnostics.Process.Start(info);
proc.WaitForExit();
var exit = proc.ExitCode;
... ommit error handler code ...
proc.Close();
}
catch (Exception e)
{
// Your exception handler here.
}
finally
{
if (File.Exists(batFilePath)) File.Delete(batFilePath);
}
});
}
这里是转储方法
private static ProcessStartInfo ProcessInfoByOS(string batFilePath)
{
ProcessStartInfo info;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
info = new ProcessStartInfo(batFilePath)
{
};
}
else
{
info = new ProcessStartInfo("sh")
{
Arguments = $"{batFilePath}"
};
}
info.CreateNoWindow = true;
info.UseShellExecute = false;
info.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
info.RedirectStandardError = true;
return info;
}