• 0

c# , simple MySQL backup solution


Question

I'm coding an app in c# that uses a MySQL database as a backend and it needs a simple backup feature

the backup will be done to a USB memory stick (probably 256MB or so)

I need a simple and very preferably free way to do this

I tried calling mysql dump from inside c# with the following code

 private void backupButtonj_Click(object sender, System.EventArgs e) {
 	 System.Diagnostics.Process proc = new System.Diagnostics.Process();
 	 proc.EnableRaisingEvents=false;
 	 proc.StartInfo.FileName="mysqldump";
 	 proc.StartInfo.Arguments="supplydirect > I:\\backup\\backup.txt";
 	 proc.Start();
 	 proc.WaitForExit();
  }

but for some reason it just flashes up the command window and doesnt do the backup

but doing the same thing from the DOS prompt works...

Link to comment
https://www.neowin.net/forum/topic/179187-c-simple-mysql-backup-solution/
Share on other sites

10 answers to this question

Recommended Posts

  • 0

yea , you were right thanks , here's the final code if anyone cares

 private void backupButtonj_Click(object sender, System.EventArgs e) {
    try {
   	 DateTime backupTime = DateTime.Now;
   	 int year = backupTime.Year;
   	 int month = backupTime.Month;
   	 int day = backupTime.Day;
   	 int hour = backupTime.Hour;
   	 int minute = backupTime.Minute;
   	 int second = backupTime.Second;
   	 int ms = backupTime.Millisecond;

   	 String tmestr = backupTime.ToString();
   	 tmestr = "I:\\"+year+"-"+month+"-"+day+"-"+hour+"-"+minute+"-"+second+"-"+ms+".txt";
   	 StreamWriter file = new StreamWriter(tmestr);
   	 ProcessStartInfo proc = new ProcessStartInfo(); 
   	 proc.FileName = "mysqldump";
   	 proc.RedirectStandardInput = false;
   	 proc.RedirectStandardOutput = true;
   	 proc.Arguments = "supplydirect";
   	 proc.UseShellExecute = false; 
   	 Process p = Process.Start(proc);
   	 string res;
   	 res = p.StandardOutput.ReadToEnd();
   	 file.WriteLine(res);
   	 p.WaitForExit(); 
   	 file.Close();
    }

    catch (IOException ex) {
   	 MessageBox.Show("Disk or other IO error , unable to backup!");
    }
  }

  • 0

While searching for backup mysql data from C#, I found this one good solution, but it did not solve my problem completely.

The problem is that, I am just getting following text in backup file instead of whole database.

  Quote
-- MySQL dump 10.10

--

-- Host: localhost Database: smartdb

-- ------------------------------------------------------

-- Server version 5.0.22-community-nt

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;

/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;

/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;

/*!40101 SET NAMES utf8 */;

/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;

/*!40103 SET TIME_ZONE='+00:00' */;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;

/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;

/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;

/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

I have modified the code as below.

  Quote
try

{

DateTime backupTime = DateTime.Now;

int year = backupTime.Year;

int month = backupTime.Month;

int day = backupTime.Day;

int hour = backupTime.Hour;

int minute = backupTime.Minute;

int second = backupTime.Second;

int ms = backupTime.Millisecond;

String tmestr = backupTime.ToString();

tmestr = "C:\\"+year+"-"+month+"-"+day+"-"+hour+"-"+minute+".sql";

StreamWriter file = new StreamWriter(tmestr);

ProcessStartInfo proc = new ProcessStartInfo();

string cmd = string.Format(@"-u{0} -p{1} -h{2} {3} > {4};", "root", "password", "localhost", "dbfile", "backup.sql");

proc.FileName = "mysqldump";

proc.RedirectStandardInput = false;

proc.RedirectStandardOutput = true;

proc.Arguments = cmd;//"-u root -p smartdb > testdb.sql";

proc.UseShellExecute = false;

Process p = Process.Start(proc);

string res;

res = p.StandardOutput.ReadToEnd();

file.WriteLine(res);

p.WaitForExit();

file.Close();

}

catch (IOException ex)

{

MessageBox.Show("Disk or other IO error , unable to backup!");

}

THANKS FOR YOUR HELP.

SHRESTHA

  • 0

The problem is about this line:

  shrestha said:
string cmd = string.Format(@"-u{0} -p{1} -h{2} {3} > {4};", "root", "password", "localhost", "dbfile", "backup.sql");

You should not include piping options in the string. also the string should not contain any semicolon ( ; ) character.

Just rewrite the line as:

string cmd = string.Format(@"-u{0} -p{1} -h{2} {3}", "root", "password", "localhost", "dbfile");

and the everything will be OK.

  • 0

Hello,

the Backup of the Database works fine like this

System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo.FileName = Path.Combine(ApplicationConfig.ApplicationDataPath, "db\\bin\\mysqldump.exe");
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.Arguments = "-h localhost --user=" + dbUser + " --password=" + dbPwd + " --databases db1 db2 --result-file " + OutputFile;
myProcess.Start();
string output = myProcess.StandardOutput.ReadToEnd();

if the output ios empty - no error occured.

But the question is: how does the restore work? I cant find a parameter like --result-file for the restore direction.

Are there other ways to do this?

Thanks

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • UI is slow but you prefer a slower UI to a snappier UI basically. Everyone is different.
    • XFX 9060 XT 16 GB is $349 on Amazon (shipped & sold by Amazon) https://www.amazon.com/dp/B0F8...p;previewDohDeal=1&th=1 People - never trust any neowin deals posted - they are the worst at seeking deals, and just want to peddle their own to make a quick buck. It's disgusting.
    • It's a grey market key - proceed at your own risk. It's baffling that neowin supports this shady stuff.
    • Arc 1.57.0 by Razvan Serea ARC browser is finally here for Windows, bringing its unique and modern approach to browsing. With a clean interface and a powerful sidebar, ARC makes managing tabs and organizing your workflow a breeze. You can group tabs, pin important pages, and quickly switch between work and personal spaces without clutter. It’s designed to be fast, customizable, and genuinely useful, making it more than just a browser—it’s a productivity tool. If you’re on Windows and want a fresh way to browse and stay organized, ARC is worth checking out. ARC browser key features: Split View: Work with multiple tabs side by side in a single window for efficient multitasking. Tab Grouping: Organize tabs into customizable groups for better workflow management. Pinned Tabs: Keep essential pages permanently accessible in the sidebar. Spaces: Create separate workspaces for different projects or personal use, reducing clutter. Sidebar Integration: Access bookmarks, notes, and tools directly from the sidebar for quick navigation. Customizable Themes: Personalize the browser’s appearance with themes and color schemes. Quick Search: Find tabs, history, or bookmarks instantly with a powerful search bar. Lightning-Fast Performance: Built for speed with optimized resource usage and minimal lag. Built-in Note-Taking: Jot down ideas or save snippets directly within the browser. Focus Mode: Hide distractions and focus on a single tab or task. Cross-Device Syncing: Seamlessly sync your data across multiple devices for a unified experience. Keyboard Shortcuts: Boost productivity with customizable shortcuts for common actions. AI-Powered Suggestions: Get smart recommendations for tabs, bookmarks, and workflows. Privacy Controls: Built-in tools for blocking trackers and managing cookies for enhanced security. Extensions Support: Compatible with popular browser extensions to extend functionality. Arc Browser 1.57.0 release notes: ''Thanks as always for using Arc. This week's release includes a bump to Chromium 137.0.7151.69, which patched three security vulnerabilities. Enjoy!'' Download: Arc Browser 1.57.0 | 1.9 MB (Freeware) View: Arc Browser Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • First Post
      Uranus_enjoyer earned a badge
      First Post
    • Week One Done
      Uranus_enjoyer earned a badge
      Week One Done
    • Week One Done
      jfam earned a badge
      Week One Done
    • First Post
      survivor303 earned a badge
      First Post
    • Week One Done
      CHUNWEI earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      427
    2. 2
      +FloatingFatMan
      237
    3. 3
      ATLien_0
      213
    4. 4
      snowy owl
      210
    5. 5
      Xenon
      160
  • Tell a friend

    Love Neowin? Tell a friend!