Click here to Skip to main content
15,903,012 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,

I am using WPF apps with MySQL database. I did create backup.sql file. Then, after create .exe file, how can I check if db exist then skip below code?

Please help me...

What I have tried:

I did used this code,

C#
private void Application_Startup(object sender, StartupEventArgs e)  
        {  
            RestoreBehavior();  
        }  


Here,How can I check here if mydb exist then skip the code?

C#
private void RestoreBehavior()  
        {  
            string constring = "server=localhost;user=root;pwd=123456;";  
            string file = @"C:\Program Files (x86)\xxxx\xxxx\backup.sql";  
            using (MySqlConnection conn = new MySqlConnection(constring))  
            {  
                using (MySqlCommand cmd = new MySqlCommand())  
                {  
                    using (MySqlBackup mb = new MySqlBackup(cmd))  
                    {  
                        cmd.Connection = conn;  
                        conn.Open();  
                        mb.ImportInfo.TargetDatabase = "mydb";/*Here,How can I check here if mydb exist then skip the code?*/
                        mb.ImportInfo.DatabaseDefaultCharSet = "utf8";  
                        mb.ImportFromFile(file);  
                    }  
                }  
            }  
        }  
Posted
Updated 28-Jan-17 8:37am

1 solution

Try:

SQL
use information_schema;
SELECT COUNT(*) FROM schemata WHERE SCHEMA_NAME="<db name here>";


C#
public bool DBExists(string conn, string dbName)
{
	bool functionReturnValue = false;

	using (MySqlConnection dbconn = new MySqlConnection(conn)) {
		using (MySqlCommand cmd = new MySqlCommand("SELECT COUNT(*) FROM information_schema.schemata WHERE SCHEMA_NAME=@dbName", conn)) {
			functionReturnValue = false;
cmd.Parameters.AddWithValue("@dbName", dbName);
			dbconn.Open();
			if (cmd.ExecuteNonQuery() != 0) {
				functionReturnValue = true;
			}
			dbconn.Close();
		}
	}
	return functionReturnValue;
}
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900