简体   繁体   中英

Copy MySQL database from C#

I want to copy/duplicate a database using C# I tried in the following way but it gave me error saying check mysql syntax.

string connStr = "server=localhost;user=root;port=3306;";
            MySqlConnection conn = new MySqlConnection(connStr);
            MySqlCommand cmd;
            string s0;

            try
            {
                conn.Open();
                s0 = "mysqldump -h localhost -u root -p testdb | mysql -h localhost -u root -p `"+dbname+"`;";
                cmd = new MySqlCommand(s0, conn);
                cmd.ExecuteNonQuery();
                conn.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            } 

No password for MySQL database. Can anyone tell me what's the issue in this code? Thanks.

If you code the call with just a -p parameter mysqldump will ask for a password, which of course you wont be able to enter as you are not running it from a command window.

You have to pass the password on the call ie -pAValidPassword (no space)

Of course this is a very insecure way of doing it as anybody wit access to your code now has access to the password!!

Documentation

You are trying to run an executable like it was a SQL command. It's not.

mysqldump is an executable that's present on your file system. To execute this app and make a backup of the db this way you have to use Shell. In C# you can use System.Diagnostics.Process to run this in a process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM