Provides a class capable of executing a SQL script containing multiple SQL statements including CREATE PROCEDURE statements that require changing the delimiter
Пример #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();
                }
            }
        }
Пример #2
0
        public void Dispose()
        {
            try
            {
                Database.Dispose();
            }
            catch (Exception)
            {
                // ignored
            }

            try
            {
                Server = null;
            }
            catch
            {
                // ignored
            }

            try
            {
                _mySqlScript = null;
            }
            catch
            {
                // ignored
            }
        }
Пример #3
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);
         }
     }
 }
        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();
             }
        }
Пример #5
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();
        }
Пример #6
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();
            }
              }
        }
Пример #7
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());
                }
            }
        }
Пример #8
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();
            }
        }
Пример #9
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();
 }
Пример #11
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();
        }
Пример #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;
        }
Пример #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);
     }
 }
Пример #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();
      }
    }
Пример #16
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();
        }
Пример #17
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;
                    script.Execute();
                }
            }
        }
Пример #18
0
        public void Dispose()
        {
            try
            {
                _database.Dispose();
            }
            catch { }

            try
            {
                _server = null;
            }
            catch { }

            try
            {
                _mySqlScript = null;
            }
            catch { }
        }
        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)
     {
     }
 }
Пример #21
0
        private void Import_InitializeVariables()
        {
            if (Command == null)
            {
                throw new Exception("MySqlCommand is not initialized. Object not set to an instance of an object.");
            }

            if (Command.Connection == null)
            {
                throw new Exception(
                          "MySqlCommand.Connection is not initialized. Object not set to an instance of an object.");
            }

            if (Command.Connection.State != ConnectionState.Open)
            {
                throw new Exception("MySqlCommand.Connection is not opened.");
            }

            _stopProcess = false;
            GetSha512HashFromPassword(ImportInfo.EncryptionPassword);
            LastError              = null;
            _timeStart             = DateTime.Now;
            _currentBytes          = 0L;
            _sbImport              = new StringBuilder();
            _mySqlScript           = new MySqlScript(Command.Connection);
            _currentProcess        = ProcessType.Import;
            _processCompletionType = ProcessEndType.Complete;
            _delimiter             = ";";

            if (ImportProgressChanged != null)
            {
                _timerReport.Start();
            }

            if (ImportInfo.TargetDatabase.Length > 0)
            {
                Import_CreateNewDatabase();
            }
        }
        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();
            }
        }
Пример #23
0
        void Import_InitializeVariables()
        {
            if (Command == null)
            {
                throw new Exception("MySqlCommand is not initialized. Object not set to an instance of an object.");
            }

            if (Command.Connection == null)
            {
                throw new Exception("MySqlCommand.Connection is not initialized. Object not set to an instance of an object.");
            }

            if (Command.Connection.State != System.Data.ConnectionState.Open)
            {
                throw new Exception("MySqlCommand.Connection is not opened.");
            }

            //_createViewDetected = false;
            //_dicImportRoutines = new Dictionary<string, bool>();
            stopProcess = false;
            //GetSHA512HashFromPassword(ImportInfo.EncryptionPassword);
            _lastError            = null;
            timeStart             = DateTime.Now;
            _currentBytes         = 0L;
            _sbImport             = new StringBuilder();
            _mySqlScript          = new MySqlScript(Command.Connection);
            currentProcess        = ProcessType.Import;
            processCompletionType = ProcessEndType.Complete;
            _delimiter            = ";";
            _lastErrorSql         = string.Empty;

            if (ImportProgressChanged != null)
            {
                timerReport.Start();
            }
        }
Пример #24
0
        private static void Create(string changesetPath, string host, string port, string database, string username, string password, string definer)
        {
            MySqlConnection conn = null;

            string createDb = "SET NET_READ_TIMEOUT = 1200;DROP DATABASE IF EXISTS " + database + ";" +
                                "CREATE DATABASE " + database + " DEFAULT CHARACTER SET utf8;" +
                                "USE " + database + ";";
            try
            {
                Console.Out.Write("Creating initial database from 00.00.00.sql ...");
                StreamReader streamReader = new StreamReader(changesetPath + "00.00.00.sql", Encoding.UTF8, false);
                string sql = createDb + streamReader.ReadToEnd();
                streamReader.Close();

                sql = Regex.Replace(sql, "DEFINER=`[^`]+`@`[^`]+`", "DEFINER=" + definer);     // replace definer

                conn = new MySqlConnection(string.Format(MYSQL_CONNECTION_STR, host, username, password, port));
                conn.Open();
                MySqlScript script = new MySqlScript(conn, sql);
                script.Error += new MySqlScriptErrorEventHandler(ScriptErrorHandler);
                script.StatementExecuted += new MySqlStatementExecutedEventHandler(ScriptStatementExecutedHandler);
                script.Execute();
            }
            catch (SQLExecuteException)
            {
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Oops!!!!\n" + e.Message);
            }
            finally
            {
                if (conn != null && conn.State != ConnectionState.Closed)
                    conn.Close();
            }
        }
Пример #25
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;
            }
        }
Пример #26
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();
      }
    }
Пример #27
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();
   }
 }
Пример #28
0
        private List <ScriptStatement> BreakIntoStatements(bool ansiQuotes, bool noBackslashEscapes)
        {
            string text = this.Delimiter;
            int    num  = 0;
            List <ScriptStatement> list           = new List <ScriptStatement>();
            List <int>             list2          = this.BreakScriptIntoLines();
            MySqlTokenizer         mySqlTokenizer = new MySqlTokenizer(this.query);

            mySqlTokenizer.AnsiQuotes       = ansiQuotes;
            mySqlTokenizer.BackslashEscapes = !noBackslashEscapes;
            for (string text2 = mySqlTokenizer.NextToken(); text2 != null; text2 = mySqlTokenizer.NextToken())
            {
                if (!mySqlTokenizer.Quoted)
                {
                    if (text2.ToLower(CultureInfo.InvariantCulture) == "delimiter")
                    {
                        mySqlTokenizer.NextToken();
                        this.AdjustDelimiterEnd(mySqlTokenizer);
                        text = this.query.Substring(mySqlTokenizer.StartIndex, mySqlTokenizer.StopIndex - mySqlTokenizer.StartIndex).Trim();
                        num  = mySqlTokenizer.StopIndex;
                    }
                    else
                    {
                        if (text.StartsWith(text2, StringComparison.OrdinalIgnoreCase) && mySqlTokenizer.StartIndex + text.Length <= this.query.Length && this.query.Substring(mySqlTokenizer.StartIndex, text.Length) == text)
                        {
                            text2 = text;
                            mySqlTokenizer.Position  = mySqlTokenizer.StartIndex + text.Length;
                            mySqlTokenizer.StopIndex = mySqlTokenizer.Position;
                        }
                        int num2 = text2.IndexOf(text, StringComparison.OrdinalIgnoreCase);
                        if (num2 != -1)
                        {
                            int num3 = mySqlTokenizer.StopIndex - text2.Length + num2;
                            if (mySqlTokenizer.StopIndex == this.query.Length - 1)
                            {
                                num3++;
                            }
                            string          text3 = this.query.Substring(num, num3 - num);
                            ScriptStatement item  = default(ScriptStatement);
                            item.text     = text3.Trim();
                            item.line     = MySqlScript.FindLineNumber(num, list2);
                            item.position = num - list2[item.line];
                            list.Add(item);
                            num = num3 + text.Length;
                        }
                    }
                }
            }
            if (num < this.query.Length - 1)
            {
                string text4 = this.query.Substring(num).Trim();
                if (!string.IsNullOrEmpty(text4))
                {
                    ScriptStatement item2 = default(ScriptStatement);
                    item2.text     = text4;
                    item2.line     = MySqlScript.FindLineNumber(num, list2);
                    item2.position = num - list2[item2.line];
                    list.Add(item2);
                }
            }
            return(list);
        }
Пример #29
0
 private void ExecuteRaw(string sql)
 {
   MySqlScript script = new MySqlScript(_utilCon, sql);
   script.Execute();
 }
Пример #30
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);
            }
        }
Пример #31
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;
        }
Пример #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);
   }
 }
Пример #33
0
 public MySqlScriptErrorEventArgs(String connectionString, Exception exception, MySqlScript script)
     : base(MethodName.ExecuteCommand, connectionString, exception)
 {
     this.MySqlScript = script;
 }
Пример #34
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;
              }
            }
              }
        }
Пример #35
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;
        }
Пример #36
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;
   }
 }