Execute() public method

Executes this instance.
public Execute ( ) : int
return int
Exemplo n.º 1
2
        protected override void ExecuteScript(DbConnection conn, string[] script)
        {
            if (!(conn is MySqlConnection))
            {
                base.ExecuteScript(conn, script);
                return;
            }

            MySqlScript scr = new MySqlScript((MySqlConnection) conn);
            {
                foreach (string sql in script)
                {
                    scr.Query = sql;
                    string sql1 = sql;
                    scr.Error += delegate { throw new Exception(sql1); };
                    scr.Execute();
                }
            }
        }
Exemplo n.º 2
0
    protected void LoadSchema(int version)
    {
      if (version < 1) return;

      MySQLMembershipProvider provider = new MySQLMembershipProvider();

      ResourceManager r = new ResourceManager("MySql.Web.Properties.Resources", typeof(MySQLMembershipProvider).Assembly);
      string schema = r.GetString(String.Format("schema{0}", version));
      MySqlScript script = new MySqlScript(conn);
      script.Query = schema;

      try
      {
        script.Execute();
      }
      catch (MySqlException ex)
      {
        if (ex.Number == 1050 && version == 7)
        {
          // Schema7 performs several renames of tables to their lowercase representation. 
          // If the current server OS does not support renaming to lowercase, then let's just continue.
          script.Query = "UPDATE my_aspnet_schemaversion SET version=7";
          script.Execute();
        }
      }
    }
Exemplo n.º 3
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("此操作会清空软件中的所有数据,如果有数据,请做好数据备份(导出)!您是否继续?", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
            {
                try
                {
                    using (MySqlConnection conn = DBA.MySqlDbAccess.GetMySqlConnection())
                    {

                        conn.Open();

                        string sql = File.ReadAllText(System.AppDomain.CurrentDomain.BaseDirectory + "xy.dll", Encoding.GetEncoding("utf-8"));
                        MySqlScript script = new MySqlScript(conn);

                        script.Query = sql;
                        int count = script.Execute();
                    }
                    MessageBox.Show("数据库已更新至最新版本!", "提示");
                    log.Info("执行数据库重置:" + DateTime.Now.ToString());
                    showversion();
                }
                catch (Exception ex)
                {
                    log.Error(ex.ToString());
                }
            }
        }
Exemplo n.º 4
0
 private void Button4_Click(object sender, EventArgs e)
 {
     if (
         MessageBox.Show(this,
             @"การสร้างฐานข้อมูลใหม่จะลบ ฐานข้อมูลเก่าออกทั้งหมด คุณต้องการจะดำเนินการต่อหรือไม่?",
             @"ลบฐานข้อมูล", MessageBoxButtons.YesNo) == DialogResult.Yes)
     {
         try
         {
             if (_conn.State != ConnectionState.Closed)
             {
                 _conn.Close();
             }
             _conn.Open();
             var sc = new MySqlScript(_conn, Settings.Default.sql);
             if (sc.Execute() >= 1)
             {
                 MessageBox.Show(@"สร้างฐานข้อมูลสำเร็จ");
             }
             else
             {
                 MessageBox.Show(@"สร้างฐานข้อมูลล้มเหลว");
             }
         }
         catch (MySqlException ex)
         {
             MessageBox.Show(ex.Message);
         }
     }
 }
Exemplo n.º 5
0
        protected override void DbCreateDatabase(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection)
        {
            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }
            MySqlConnection conn = connection as MySqlConnection;

            if (conn == null)
            {
                throw new ArgumentException(Resources.ConnectionMustBeOfTypeMySqlConnection, "connection");
            }
            // Ensure a valid provider manifest token.
            string providerManifestToken = this.GetDbProviderManifestToken(connection);
            string query = DbCreateDatabaseScript(providerManifestToken, storeItemCollection);

            using (MySqlConnection c = new MySqlConnection())
            {
                MySqlConnectionStringBuilder sb = new MySqlConnectionStringBuilder(conn.ConnectionString);
                string dbName = sb.Database;
                sb.Database        = null;
                c.ConnectionString = sb.ConnectionString;
                c.Open();

                string      fullQuery = String.Format("CREATE DATABASE `{0}`; USE `{0}`; {1}", dbName, query);
                MySqlScript s         = new MySqlScript(c, fullQuery);
                s.Execute();
            }
        }
        public void CanCreateDBScriptWithDateTimePrecision()
        {
            if (Version < new Version(5, 6, 5)) return;

             MySqlConnection c = new MySqlConnection(conn.ConnectionString);
             c.Open();

             var script = new MySqlScript(c);
             using (var ctx = new datesTypesEntities())
             {
               MySqlCommand query = new MySqlCommand("Create database test_types", c);
               query.Connection = c;
               query.ExecuteNonQuery();
               c.ChangeDatabase("test_types");

               script.Query = ctx.CreateDatabaseScript();
               script.Execute();

               query = new MySqlCommand("Select Column_name, Is_Nullable, Data_Type, DateTime_Precision from information_schema.Columns where table_schema ='" + c.Database + "' and table_name = 'Products' and column_name ='DateTimeWithPrecision'", c);
               query.Connection = c;
               MySqlDataReader reader = query.ExecuteReader();
               while (reader.Read())
               {
              Assert.AreEqual("DateTimeWithPrecision", reader[0].ToString());
              Assert.AreEqual("NO", reader[1].ToString());
              Assert.AreEqual("datetime", reader[2].ToString());
              Assert.AreEqual("3", reader[3].ToString());
               }
               reader.Close();
               ctx.DeleteDatabase();
               c.Close();
             }
        }
Exemplo n.º 7
0
        public override void Setup()
        {
            base.Setup();

              // Replace existing listeners with listener for testing.
              Trace.Listeners.Clear();
              Trace.Listeners.Add(this.asertFailListener);

              ResourceManager r = new ResourceManager("MySql.Data.Entity.Tests.Properties.Resources", typeof(BaseEdmTest).Assembly);
              string schema = r.GetString("schema");
              MySqlScript script = new MySqlScript(conn);
              script.Query = schema;
              script.Execute();

              // now create our procs
              schema = r.GetString("procs");
              script = new MySqlScript(conn);
              script.Delimiter = "$$";
              script.Query = schema;
              script.Execute();

              //ModelFirstModel1
              schema = r.GetString("ModelFirstModel1");
              script = new MySqlScript(conn);
              script.Query = schema;
              script.Execute();

              MySqlCommand cmd = new MySqlCommand("DROP DATABASE IF EXISTS `modeldb`", rootConn);
              cmd.ExecuteNonQuery();
        }
Exemplo n.º 8
0
		// http://bugs.mysql.com/bug.php?id=46429
		public override void run_sql(string sql_to_run)
		{
			if (string.IsNullOrEmpty(sql_to_run)) return;

			// TODO Investigate how pass CommandTimeout into commands which will be during MySqlScript execution.
			var connection = server_connection.underlying_type().downcast_to<MySqlConnection>();
			var script = new MySqlScript(connection, sql_to_run);
			script.Execute();
		}
 public static void RecreateMysqlDatabase()
 {
     if (!Connection.State.ToString().Equals("Open"))
     {
         Connection.Open();
     }
     var runScript = new MySqlScript(Connection, Properties.Settings.Default.WipeDatabase);
     runScript.Execute();
     Connection.Close();
 }
Exemplo n.º 10
0
        public override int ExecuteScript(DbConnection conn, string sql, string delimiter)
        {
            MySqlScript script = new MySqlScript((MySqlConnection) conn, sql);

            if (!string.IsNullOrEmpty(delimiter))
            {
                script.Delimiter = delimiter;
            }

            return script.Execute();
        }
Exemplo n.º 11
0
        void Import_AppendLineAndExecute(string line)
        {
            _sbImport.AppendLine(line);
            if (!line.EndsWith(_delimiter))
            {
                return;
            }

            _mySqlScript.Query     = _sbImport.ToString();
            _mySqlScript.Delimiter = _delimiter;
            _mySqlScript.Execute();
            _sbImport = new StringBuilder();
        }
Exemplo n.º 12
0
        private bool  CreateDb()
        {
            bool bRs = false;

            string connStr = string.Format("server={0};user={1};database=;password={2};charset=utf8;Allow User Variables=True", txbDbName.Text.Trim(), txbUs.Text.Trim(), txbPw.Text.Trim());
            MySqlConnection conn = new MySqlConnection(connStr);

            try
            {
                Console.WriteLine("Connecting to MySQL...");
                conn.Open();

                string sql = File.ReadAllText("createDb.sql");
                MySqlScript script = new MySqlScript(conn);

                script.Query = sql;
                //script.Delimiter = "??";
                int count = script.Execute();
                
                Console.WriteLine("Executed " + count + " statement(s)");
                //script.Delimiter = ";";
                conn.Close();
                Console.WriteLine("Delimiter: " + script.Delimiter);
                Console.WriteLine("Query: " + script.Query);


                /////////////
                connStr = string.Format("server={0};user={1};database=ztst;password={2};charset=utf8;Allow User Variables=True", txbDbName.Text.Trim(), txbUs.Text.Trim(), txbPw.Text.Trim());
                conn = new MySqlConnection(connStr);
                Console.WriteLine("Connecting to MySQL...");
                conn.Open();

                sql = File.ReadAllText("ztst.sql");
                script = new MySqlScript(conn);
                script.Query = sql;
                //script.Delimiter = "??";
                count = script.Execute();
                Console.WriteLine("Executed " + count + " statement(s)");
                //script.Delimiter = ";";
                conn.Close();
            }
            catch (Exception ex)
            {
                bRs = false;
                Console.WriteLine(ex.ToString());
            }

            //conn.Close();
            Console.WriteLine("Done.");
            return bRs;
        }
Exemplo n.º 13
0
        public static bool CheckAndUpData()
        {
            DataTable dt = DBA.MySqlDbAccess.GetDataTable(CommandType.Text, "select * from cfg_dbversion");
            string[] files = Directory.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory + "MySqlScript");
            List<int> versionhis = new List<int>();
            foreach (var file in files)
            {
                try
                {
                    versionhis.Add(Convert.ToInt32(Path.GetFileNameWithoutExtension(file)));
                }
                catch (Exception)
                {
                    continue;
                }
            }
            int newserion = versionhis.Max();
            int exeversion = Convert.ToInt32(dt.Rows[0]["dbversion"].ToString());
            string updatatime = dt.Rows[0]["updatetime"].ToString();
            if (newserion == exeversion)
            {
                return true;
            }
            else
            {
                using (MySqlConnection conn = DBA.MySqlDbAccess.GetMySqlConnection())
                {
                    conn.Open();
                    for (int i = exeversion + 1; i <= newserion; i++)
                    {
                        string sql = File.ReadAllText(System.AppDomain.CurrentDomain.BaseDirectory + "MySqlScript\\" + i, Encoding.GetEncoding("utf-8"));
                        MySqlScript script = new MySqlScript(conn);
                        script.Query = sql;
                        int count = script.Execute();
                        DBA.MySqlDbAccess.ExecNoQuery(CommandType.Text, string.Format("update cfg_dbversion set dbversion={0},updatetime='{1}'", i, DateTime.Now));

                        //try
                        //{
                        //}
                        //catch (Exception ex)
                        //{
                        //    throw ex;
                        //}

                    }
                }
                return true;
            }
        }
 private void ExecuteScript(string fileName)
 {
     MySqlConnection connection = (MySqlConnection)DbConnectionFactory.CreateAndOpenConnection();
     try
     {
         string fullPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\Resources\" + fileName + ".sql";
         MySqlScript script = new MySqlScript(connection, File.ReadAllText(fullPath));
         script.Delimiter = ";";
         script.Execute();
     }
     finally
     {
         DbConnectionFactory.CloseDisposeConnection(connection);
     }
 }
Exemplo n.º 15
0
    public SetUp()
    {
      Initialize();
      LoadBaseConfiguration();

      using (MySqlConnection connection = new MySqlConnection(ConnectionStringRootMaster))
      {
        connection.Open();
        MySqlScript script = new MySqlScript(connection);

        // Sets users
        script.Query = Properties.Resources._01_Startup_root_script;
        script.Execute();

        // Sets database objects
        script.Query = string.Format(Properties.Resources._02_Startup_script, databaseName);
        script.Execute();
      }
    }
        public void ExecuteScripts()
        {
            if (string.IsNullOrEmpty(ConnectionString))
                throw new ArgumentNullException("Connection string shouldn´t be null.");

            if (ScriptsFiles == null)
                throw new ArgumentNullException("You must add a script to execute.");

            Assembly thisAssembly = Assembly.GetCallingAssembly();

            MySqlConnection connMySql = null;
            try {
                connMySql = new MySqlConnection(ConnectionString);
                foreach (string file in ScriptsFiles) {
                    string result = string.Empty;
                    using (Stream stream = thisAssembly.GetManifestResourceStream(file)) {
                        using (StreamReader reader = new StreamReader(stream)) {
                            result = reader.ReadToEnd();
                        }
                    }

                    MySqlScript script = new MySqlScript(connMySql, result);
                    script.Delimiter = "$$";
                    script.Execute();
                }

            } catch (MySqlException ex) {
                throw new Exception("Problems with the database sorry...", ex);
            } catch (Exception ex) {
                throw;
            } finally {
                connMySql.Close();
            }

            //sql server
            //FileInfo file = new FileInfo("C:\\myscript.sql");
            //string script = file.OpenText().ReadToEnd();
            //SqlConnection conn = new SqlConnection(sqlConnectionString);
            //Server server = new Server(new ServerConnection(conn));
            //server.ConnectionContext.ExecuteNonQuery(script);
        }
 private void initiateDB()
 {
     try
     {
         mysql_connection = new MySqlConnection(connectionString);
         mysql_connection.Open();
         //use the database created and then execute sql scripts to create table and populate with some sample data
         string sqlStatement = "USE " + mysqldbname + ";";
         MySqlCommand cmd = new MySqlCommand(sqlStatement, mysql_connection);
         cmd.ExecuteNonQuery();
         MySqlScript script1 = new MySqlScript(mysql_connection, File.ReadAllText("sql-scripts/create-schema.sql"));
         script1.Delimiter = "$$";
         script1.Execute();
         MySqlScript script2 = new MySqlScript(mysql_connection, File.ReadAllText("sql-scripts/insert-towns.sql"));
         script2.Delimiter = "$$";
         script2.Execute();
     }
     catch (MySqlException ex)
     {
     }
 }
Exemplo n.º 18
0
        void Import_AppendLineAndExecute(string line)
        {
            _sbImport.Append(line);

            string _query = _sbImport.ToString();

            if (_query.StartsWith("DELIMITER ", StringComparison.OrdinalIgnoreCase))
            {
                _mySqlScript.Query     = _sbImport.ToString();
                _mySqlScript.Delimiter = _delimiter;
                _mySqlScript.Execute();
            }
            else
            {
                Command.CommandText = _query;
                Command.ExecuteNonQuery();
            }

            _sbImport = new StringBuilder();

            GC.Collect();
        }
        protected override void DbCreateDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");
            MySqlConnection conn = connection as MySqlConnection;
            if (conn == null)
                throw new ArgumentException(Resources.ConnectionMustBeOfTypeMySqlConnection, "connection");

            string query = DbCreateDatabaseScript(null, storeItemCollection);

            using (MySqlConnection c = new MySqlConnection())
            {
                MySqlConnectionStringBuilder sb = new MySqlConnectionStringBuilder(conn.ConnectionString);
                string dbName = sb.Database;
                sb.Database = "mysql";
                c.ConnectionString = sb.ConnectionString;
                c.Open();

                string fullQuery = String.Format("CREATE DATABASE `{0}`; USE `{0}`; {1}", dbName, query);
                MySqlScript s = new MySqlScript(c, fullQuery);
                s.Execute();
            }
        }
Exemplo n.º 20
0
        private MySql.Data.MySqlClient.MySqlConnection OpenConnection(string username, string password) {
            string connString = "server=" + Properties.Settings.Default.db_server + ";"
                                + "uid=" + username + ";"
                                + "pwd=" + password + ";"
                                + "; port=5715; database=inventralalab;";

            try {
                connection = new MySql.Data.MySqlClient.MySqlConnection();
                connection.ConnectionString = connString;
                connection.Open();
                Properties.Settings.Default.Save();
                string[] files = Directory.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory + "../../db/tables");
                foreach (string file in files) {
                    MySqlScript script = new MySqlScript(connection, File.ReadAllText(file));
                    script.Execute();
                }
                
                return connection;
            }
            catch (MySql.Data.MySqlClient.MySqlException ex) {
                MessageBox.Show(ex.Message);
                return null;
            }
        }
Exemplo n.º 21
0
 /// <summary>
 /// Writes locals values back to the routine scope.
 /// </summary>
 public void CommitLocals()
 {
   StringBuilder sql = new StringBuilder();
   foreach (StoreType st in CurrentScope.Variables.Values)
   {
     if (st.VarKind == VarKindEnum.Internal) continue;
     if (st.ValueChanged)
     {
       //sql.Append("replace `serversidedebugger`.`DebugScope`( DebugSessionId, DebugScopeLevel, VarName, VarValue ) ").
       //  AppendFormat("values ( {0}, {1}, '{2}', cast( {3} as binary ) );", DebugSessionId, _scopeLevel, st.Name, st.WrapValue()).AppendLine();
       sql.AppendFormat(" call `serversidedebugger`.`SetDebugScopeVar`( {0}, {1}, '{2}', cast( {3} as binary ) );", DebugSessionId, _scopeLevel, st.Name, st.WrapValue()).AppendLine();
       st.ValueChanged = false;
     }
   }
   if (sql.Length != 0)
   {
     MySqlScript script = new MySqlScript(_utilCon, sql.ToString());
     script.Execute();
   }
 }
 void Execute(string sql)
 {
     try
     {
         using (MySqlConnection conn = new MySqlConnection(Program.ConnectionString))
         {
             MySqlScript script = new MySqlScript(conn);
             script.Query = sql;
             script.Execute();
             script = null;
         }
         MessageBox.Show("Done");
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Exemplo n.º 23
0
 private void ExecuteRaw(string sql)
 {
   MySqlScript script = new MySqlScript(_utilCon, sql);
   script.Execute();
 }
Exemplo n.º 24
0
    private void ExecuteSetupScripts()
    {
      MySqlConnection con = new MySqlConnection(_connection.ConnectionString);      
      Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MySql.Debugger.MySql_Scripts.Schema.sql");
      StreamReader sr = new StreamReader(stream);
      string sql = sr.ReadToEnd();
      sr.Close();

      con.Open();
      try
      {
        MySqlScript script = new MySqlScript(con);
        script.Query = sql;
        script.Delimiter = "//";
        script.Execute();

        stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MySql.Debugger.MySql_Scripts.Logic.sql");
        sr = new StreamReader(stream);
        sql = sr.ReadToEnd();
        sr.Close();
        script.Query = sql;
        script.Execute();
      }
      finally
      {
        con.Close();
      }
    }
Exemplo n.º 25
0
        public override void Setup()
        {
            base.Setup();

            ResourceManager r = new ResourceManager("MySql.Data.Entity.Tests.Properties.Resources", typeof(BaseEdmTest).Assembly);
            string schema = r.GetString("schema");
            MySqlScript script = new MySqlScript(conn);
            script.Query = schema;
            script.Execute();

            // now create our procs
            schema = r.GetString("procs");
            script = new MySqlScript(conn);
            script.Delimiter = "$$";
            script.Query = schema;
            script.Execute();

            MySqlCommand cmd = new MySqlCommand("DROP DATABASE IF EXISTS `modeldb`", rootConn);
            cmd.ExecuteNonQuery();
        }
Exemplo n.º 26
0
        private void btnInstall_Click(object sender, EventArgs e)
        {
            if (machine == "Server")
            {
                if (btnInstall.Text == "Upgrade")
                {
                    upgrade();
                    this.Close();
                }
                else if (btnInstall.Text == "OK")
                {
                    string mysqlDir = "", iniDir = "";
                    if (txbxLocation.Text != "")
                    {
                        mysqlDir = txbxLocation.Text;
                    }
                    else
                    {
                        mysqlDir = ProgramFilesx86() + "\\MySql\\bin\\mysql";
                    }

                    //iniDir = mysqlDir.Substring(0, mysqlDir.IndexOf("bin")-1);
                    //if (File.Exists(iniDir + "my.ini"))
                    //{
                    //    StreamWriter sw = File.AppendText(iniDir + "my.ini");
                    //    sw.WriteLine("event_scheduler=ON");
                    //    sw.Close();
                    //}

                    string args = " -u" + txbUsername.Text + " -p" + txbPassword.Text + " --execute \"CREATE USER `osae`@`%` IDENTIFIED BY \'osaePass\'\";";
                    Process p = Process.Start(mysqlDir, args);
                    p.WaitForExit();

                    string ConnectionString = string.Format("Uid={0};Password={1};Server={2};Port={3}", txbUsername.Text, txbPassword.Text, "localhost", "3306");
                    connection = new MySqlConnection(ConnectionString);
                    MySqlCommand command;
                    MySqlDataAdapter adapter;
                    DataSet dataset = new DataSet();
                    command = new MySqlCommand("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'osae'", connection);
                    adapter = new MySqlDataAdapter(command);
                    adapter.Fill(dataset);
                    connection.Close();
                    int count = dataset.Tables[0].Rows.Count;

                    args = " -u" + txbUsername.Text + " -p" + txbPassword.Text + " --execute \"GRANT ALL ON osae.* TO `osae`@`%`\";";
                    p = Process.Start(mysqlDir, args);
                    p.WaitForExit();

                    if (count == 1)
                    {
                        try
                        {
                            ConnectionString = string.Format("Uid={0};Password={1};Server={2};Port={3};Database={4};allow user variables=true", txbUsername.Text, txbPassword.Text, "localhost", "3306", "osae");
                            connection = new MySqlConnection(ConnectionString);

                            connection.Open();
                            dataset = new DataSet();
                            command = new MySqlCommand("select property_value from osae_object_property p inner join osae_object_type_property tp on p.object_type_property_id = tp.property_id inner join osae_object o on o.object_id = p.object_id where object_name = 'SYSTEM' and property_name = 'DB Version'", connection);
                            adapter = new MySqlDataAdapter(command);
                            adapter.Fill(dataset);
                            if (dataset.Tables[0].Rows[0][0].ToString() == "")
                                current = "0.1.0";
                            else
                                current = dataset.Tables[0].Rows[0][0].ToString();
                            if (current != newVersion)
                            {
                                upgrade();
                            }
                            connection.Close();
                            this.Close();
                        }
                        catch
                        {
                            MessageBox.Show("Connection error.  Please check password.");
                        }
                    }
                    else
                    {

                        MySqlScript script = new MySqlScript(connection, File.ReadAllText(directory + "\\osae.sql"));
                        script.Execute();

                        script = new MySqlScript(connection, "SET GLOBAL event_scheduler=ON;");
                        script.Execute();

                        connection.Close();

                        MessageBox.Show("Database installed successfully.");
                        this.Close();
                    }
                }
                else
                    this.Close();
            }
            else if (btnInstall.Text == "OK")
            {
                ModifyRegistry myRegistry = new ModifyRegistry();
                myRegistry.SubKey = "SOFTWARE\\OSAE\\DBSETTINGS";
                myRegistry.Write("DBCONNECTION", txbUsername.Text);
                myRegistry.Write("DBPORT", txbPassword.Text);
                this.Close();
            }
        }
Exemplo n.º 27
0
        private void upgrade()
        {
            lb_Progress.Visible = true;
            installationProgressBar.Visible = true;

            session.Log("Upgrading...");
            string[] version = current.Split('.');
            int major = Int32.Parse(version[0]);
            int minor = Int32.Parse(version[1]);
            int bug = Int32.Parse(version[2]);

            string[] updateScripts = Directory.GetFiles(directory, @"*.sql", SearchOption.TopDirectoryOnly);
            List<string> scripts = new List<string>();

            foreach (string s in updateScripts)
            {
                if (s.Substring(directory.Length + 1).Contains("-"))
                {
                    string[] vers = s.Substring(directory.Length).Split('-');
                    string[] nums = vers[0].Split('.');

                    if (Int32.Parse(nums[0]) >= major)
                    {
                        if (Int32.Parse(nums[1]) >= minor)
                        {
                            if (Int32.Parse(nums[2]) >= bug)
                            {
                                scripts.Add(s.Substring(directory.Length));
                                session.Log("Found upgrade script: " + s.Substring(directory.Length));
                            }
                        }
                    }
                }
            }
            scripts.Sort();
            int max = scripts.Count;
            int count = 1;
            try
            {
                foreach (string s in scripts)
                {
                    MySqlScript script = new MySqlScript(connection, File.ReadAllText(directory + "\\" + s));
                    //script.Delimiter = "$$";
                    script.Execute();
                    decimal percent = count / max;
                    installationProgressBar.Value = (int)Math.Round(percent, 0);
                    count++;
                    session.Log("Upgrade script executed successfully: " + s);
                }
                connection.Close();
                lblError.Text = "Database upgraded successfully.";
                btnClose.Visible = true;

            }
            catch (Exception ex)
            {
                lblError.Text = "Database upgrade failed.";
                MessageBox.Show("Upgrade script failed: " + ex.Message);
                session.Log("Upgrade script failed: " + ex.Message);
            }
            installationProgressBar.Value = 100;
        }
Exemplo n.º 28
0
        private void Install()
        {
            // DB not found.  Need to install.
            session.Log("No OSA database found.  We need to install it.");

            lb_Progress.Visible = true;
            installationProgressBar.Visible = true;

            MySqlCommand command;
            MySqlDataAdapter adapter;
            DataSet dataset = new DataSet();
            MySqlScript script;
            command = new MySqlCommand("select User from mysql.user where User = '******'", connection);
            adapter = new MySqlDataAdapter(command);
            adapter.Fill(dataset);
            connection.Close();
            int count = dataset.Tables[0].Rows.Count;
            installationProgressBar.Value = 25;

            if (count == 0)
            {
                script = new MySqlScript(connection, "CREATE USER `osae`@`%` IDENTIFIED BY 'osaePass';");
                script.Execute();
            }
            installationProgressBar.Value = 50;
            script = new MySqlScript(connection, "GRANT SUPER ON *.* TO `osae`@`%`;GRANT ALL PRIVILEGES ON *.* TO 'osae'@'%' WITH GRANT OPTION;");
            script.Execute();
            installationProgressBar.Value = 75;
            script = new MySqlScript(connection, File.ReadAllText(directory + @"osae.sql"));
            script.Execute();
            connection.Close();

            installationProgressBar.Style = ProgressBarStyle.Blocks;
            installationProgressBar.Value = 100;

            lblError.ForeColor = System.Drawing.Color.Green;
            lblError.Text = "Success!";
            btnClose.Visible = true;

            txbUsername.Text = "osae";
            txbPassword.Text = "osaePass";
            SetRegistryKeys();
        }
Exemplo n.º 29
0
        public bool RunScript(string script, string overrideConnectionInfo)
        {
            if ((script == null) || (script.Trim().Length == 0)) return true;

            bool result = false;
            MySqlConnection connection;

            if (
                (overrideConnectionInfo != null)
                && (overrideConnectionInfo.Length > 0)
              )
            {
                connection = new MySqlConnection(overrideConnectionInfo);
            }
            else
            {
                connection = new MySqlConnection(writeConnectionString);
            }

            connection.Open();

            MySqlTransaction transaction = connection.BeginTransaction();

            try
            {
                // this fixed the problems with mysql 5.1
                MySqlScript mySqlScript = new MySqlScript(connection, script);
                mySqlScript.Execute();

                //this worked in all versions of mysql prior to 5.1
                //MySqlHelper.ExecuteNonQuery(
                //    connection,
                //    script, 
                //    null);

                transaction.Commit();
                result = true;

            }
            catch (MySqlException ex)
            {
                transaction.Rollback();
                log.LogError("Db.RunScript failed", ex);
                throw;
            }
            finally
            {
                connection.Close();

            }

            return result;
        }
Exemplo n.º 30
0
 private void MultipleThreadsWorkerScript(object ev)
 {
   MySqlScript script = new MySqlScript();
   script.Query = "show variables like '%ssl%'";
   (ev as ManualResetEvent).WaitOne();
   string strConn = GetConnectionString(true) + ";Pooling=true;";
   MySqlConnection c = new MySqlConnection(strConn);
   
   int result;
   script.Connection = c;
   try
   {
     for (int i = 0; i < 10; i++)
     {
       c.Open();
       result = script.Execute();
       c.Close();
     }
   }
   catch (InvalidOperationException ioe)
   {
     //Assert.AreEqual("Collection was modified; enumeration operation may not execute.", ioe.Message );
     //Assert.Fail();
     lastException = ioe;
   }
   catch (Exception e)
   {
     lastException = e;
   }
 }
Exemplo n.º 31
0
        private static void UpgradeToCurrent(string connectionString, int version)
        {
            ResourceManager r = new ResourceManager("MySql.Web.Properties.Resources",
              typeof(SchemaManager).Assembly);

              if (version == Version) return;

              using (MySqlConnection connection = new MySqlConnection(connectionString))
              {
            connection.Open();

            for (int ver = version + 1; ver <= Version; ver++)
            {
              string schema = r.GetString(String.Format("schema{0}", ver));
              MySqlScript script = new MySqlScript(connection);
              script.Query = schema;

              try
              {
            script.Execute();
              }
              catch (MySqlException ex)
              {
            if (ex.Number == 1050 && ver == 7)
            {
              // Schema7 performs several renames of tables to their lowercase representation.
              // If the current server OS does not support renaming to lowercase, then let's just continue.
              script.Query = "UPDATE my_aspnet_schemaversion SET version=7";
              script.Execute();
              continue;
            }
            throw ex;
              }
            }
              }
        }
Exemplo n.º 32
0
 private void ExecuteScript(string sql)
 {
   tabControl1.TabPages.Clear();
   MySqlScript script = new MySqlScript((MySqlConnection)connection, sql);
   try
   {
     int rows = script.Execute();
     messages.Text = String.Format("{0} row(s) affected", rows);
   }
   catch (Exception ex)
   {
     messages.Text = ex.Message;
   }
   finally
   {
     tabControl1.TabPages.Add(messagesPage);
   }
 }
Exemplo n.º 33
0
        void ExecuteSQL(int q)
        {
            try
            {
                using (MySqlConnection conn = new MySqlConnection(Program.ConnectionString))
                {
                    string sql = textBox1.Text.Trim();

                    if (q == 2)
                    {
                        MySqlScript script = new MySqlScript(conn);
                        script.Query = sql;
                        int i = script.Execute();
                        dt = new DataTable();
                        dt.Columns.Add("Result");
                        dt.Rows.Add(i + " statement(s) executed.");
                        BindData();
                    }
                    else
                    {
                        if (sql.StartsWith("select", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("show", StringComparison.OrdinalIgnoreCase))
                        {
                            if (sql.StartsWith("select", StringComparison.OrdinalIgnoreCase))
                            {
                                if (!sql.ToLower().Contains(" limit "))
                                {
                                    if (sql.EndsWith(";"))
                                    {
                                        sql = sql.Remove(sql.Length - 1);

                                    }
                                    sql += " LIMIT 0,3000;";
                                    textBox1.Text = sql;
                                    textBox1.Refresh();
                                }
                            }

                            using (MySqlCommand cmd = new MySqlCommand())
                            {
                                cmd.Connection = conn;
                                conn.Open();
                                dt = QueryExpress.GetTable(cmd, sql);
                                BindData();
                            }
                        }
                        else
                        {
                            using (MySqlCommand cmd = new MySqlCommand())
                            {
                                cmd.Connection = conn;
                                conn.Open();
                                cmd.CommandText = sql;
                                int i = cmd.ExecuteNonQuery();
                                dt = new DataTable();
                                dt.Columns.Add("Results");
                                dt.Rows.Add(i + " row(s) affected by the last command.");
                                BindData();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WriteError(ex);
            }
        }