Esempio n. 1
0
    /// <summary>
    /// Executes a single command against a MySQL database.  The <see cref="MySqlConnection"/> is assumed to be
    /// open when the method is called and remains open after the method completes.
    /// </summary>
    /// <param name="connection"><see cref="MySqlConnection"/> object to use</param>
    /// <param name="commandText">SQL command to be executed</param>
    /// <param name="commandParameters">Array of <see cref="MySqlParameter"/> objects to use with the command.</param>
    /// <returns></returns>
    public static int ExecuteNonQuery(MySqlConnection connection, string commandText, params MySqlParameter[] commandParameters)
    {
      //create a command and prepare it for execution
      MySqlCommand cmd = new MySqlCommand();
      cmd.Connection = connection;
      cmd.CommandText = commandText;
      cmd.CommandType = CommandType.Text;

      if (commandParameters != null)
        foreach (MySqlParameter p in commandParameters)
          cmd.Parameters.Add(p);

      int result = cmd.ExecuteNonQuery();
      cmd.Parameters.Clear();

      return result;
    }
Esempio n. 2
0
        private string SetUserVariables(MySqlParameterCollection parms, bool preparing)
        {
            StringBuilder setSql = new StringBuilder();

              if (serverProvidingOutputParameters) return setSql.ToString();

              string delimiter = String.Empty;
              foreach (MySqlParameter p in parms)
              {
            if (p.Direction != ParameterDirection.InputOutput) continue;

            string pName = "@" + p.BaseName;
            string uName = "@" + ParameterPrefix + p.BaseName;
            string sql = String.Format("SET {0}={1}", uName, pName);

            if (command.Connection.Settings.AllowBatch && !preparing)
            {
              setSql.AppendFormat(CultureInfo.InvariantCulture, "{0}{1}", delimiter, sql);
              delimiter = "; ";
            }
            else
            {
              MySqlCommand cmd = new MySqlCommand(sql, command.Connection);
              cmd.Parameters.Add(p);
              cmd.ExecuteNonQuery();
            }
              }
              if (setSql.Length > 0)
            setSql.Append("; ");
              return setSql.ToString();
        }
Esempio n. 3
0
 /// <summary>
 /// Reset SQL_SELECT_LIMIT that could have been modified by CommandBehavior.
 /// </summary>
 internal void ResetSqlSelectLimit()
 {
     // if we are supposed to reset the sql select limit, do that here
       if (resetSqlSelect)
       {
     resetSqlSelect = false;
     MySqlCommand command = new MySqlCommand("SET SQL_SELECT_LIMIT=DEFAULT", connection);
     command.internallyCreated = true;
     command.ExecuteNonQuery();
       }
 }
Esempio n. 4
0
		public void CancelQuery(int timeout)
		{
			using (MySqlConnection c = Clone())
			{
				c.isKillQueryConnection = true;
				c.Open();
				string commandText = "KILL QUERY " + ServerThread;
				MySqlCommand cmd = new MySqlCommand(commandText, c);
				cmd.CommandTimeout = timeout;
				cmd.ExecuteNonQuery();
			}
		}
Esempio n. 5
0
    /// <summary>
    /// Executes this instance.
    /// </summary>
    /// <returns>The number of statements executed as part of the script.</returns>
	public int Execute()
	{
		bool openedConnection = false;

		if (connection == null)
			throw new InvalidOperationException(Resources.ConnectionNotSet);
		if (query == null || query.Length == 0)
			return 0;

		// next we open up the connetion if it is not already open
		if (connection.State != ConnectionState.Open)
		{
			openedConnection = true;
			connection.Open();
		}

		// since we don't allow setting of parameters on a script we can 
		// therefore safely allow the use of user variables.  no one should be using
		// this connection while we are using it so we can temporarily tell it
		// to allow the use of user variables
		bool allowUserVars = connection.Settings.AllowUserVariables;
		connection.Settings.AllowUserVariables = true;

		try
		{
			bool ansiQuotes = -1 != -1;
			bool noBackslashEscapes = -1 != -1;

			// first we break the query up into smaller queries
			List<ScriptStatement> statements = BreakIntoStatements(ansiQuotes, noBackslashEscapes);

			int count = 0;
			MySqlCommand cmd = new MySqlCommand(null, connection);
			foreach (ScriptStatement statement in statements)
			{
				if (String.IsNullOrEmpty(statement.text)) continue;
				cmd.CommandText = statement.text;
				try
				{
					cmd.ExecuteNonQuery();
					count++;
					OnQueryExecuted(statement);
				}
				catch (Exception ex)
				{
					if (Error == null)
						throw;
					if (!OnScriptError(ex))
						break;
				}
			}
			OnScriptCompleted();
			return count;
		}
		finally
		{
			connection.Settings.AllowUserVariables = allowUserVars;
			if (openedConnection)
			{
				connection.Close();
			}
		}
	}
Esempio n. 6
0
		public new MySqlTransaction BeginTransaction(IsolationLevel iso)
		{
			//TODO: check note in help
			if (State != ConnectionState.Open)
				Throw(new InvalidOperationException(Resources.ConnectionNotOpen));

			// First check to see if we are in a current transaction
			if (driver.HasStatus(ServerStatusFlags.InTransaction))
				Throw(new InvalidOperationException(Resources.NoNestedTransactions));

			MySqlTransaction t = new MySqlTransaction(this, iso);

			MySqlCommand cmd = new MySqlCommand("", this);

			cmd.CommandText = "SET SESSION TRANSACTION ISOLATION LEVEL ";
			switch (iso)
			{
				case IsolationLevel.ReadCommitted:
					cmd.CommandText += "READ COMMITTED";
					break;
				case IsolationLevel.ReadUncommitted:
					cmd.CommandText += "READ UNCOMMITTED";
					break;
				case IsolationLevel.RepeatableRead:
					cmd.CommandText += "REPEATABLE READ";
					break;
				case IsolationLevel.Serializable:
					cmd.CommandText += "SERIALIZABLE";
					break;
				case IsolationLevel.Chaos:
					Throw(new NotSupportedException(Resources.ChaosNotSupported));
					break;
				case IsolationLevel.Snapshot:
					Throw(new NotSupportedException(Resources.SnapshotNotSupported));
					break;
			}

			cmd.ExecuteNonQuery();

			cmd.CommandText = "BEGIN";
			cmd.ExecuteNonQuery();

			return t;
		}
Esempio n. 7
0
	public virtual void Configure(MySqlConnection connection)
	{
		//bool firstConfigure = false;

		// if we have not already configured our server variables
		// then do so now
		//if (serverProps == null)
		//{
		//    firstConfigure = true;

		//    // if we are in a pool and the user has said it's ok to cache the
		//    // properties, then grab it from the pool
		//    if (Pool != null && Settings.CacheServerProperties)
		//    {
		//        if (Pool.ServerProperties == null)
		//            Pool.ServerProperties = LoadServerProperties(connection);
		//        serverProps = Pool.ServerProperties;
		//    }
		//    else
		//        serverProps = LoadServerProperties(connection);


		//}
		if (charSets != null)
			LoadCharacterSets(connection);

		// if the user has indicated that we are not to reset
		// the connection and this is not our first time through,
		// then we are done.
		if (!Settings.ConnectionReset) return;

		string charSet = connectionString.CharacterSet;
		if (charSet == null || charSet.Length == 0)
		{
			if (serverCharSetIndex >= 0)
				charSet = (string)charSets[serverCharSetIndex];
			else
				charSet = serverCharSet;
		}

		// now tell the server which character set we will send queries in and which charset we
		// want results in
		MySqlCommand charSetCmd = new MySqlCommand("SET character_set_results=NULL",
						  connection);
		charSetCmd.InternallyCreated = true;
		const string CLIENT_CHAR_SET = "latin1";
		const string CONN_CHAR_SET = "latin1";
		if ((CLIENT_CHAR_SET != null && CLIENT_CHAR_SET != charSet) ||
		  (CONN_CHAR_SET != null && CONN_CHAR_SET != charSet))
		{
			MySqlCommand setNamesCmd = new MySqlCommand("SET NAMES " + charSet, connection);
			setNamesCmd.InternallyCreated = true;
			setNamesCmd.ExecuteNonQuery();
		}
		charSetCmd.ExecuteNonQuery();

		if (charSet != null)
			Encoding = CharSetMap.GetEncoding(Version, charSet);
		else
			Encoding = CharSetMap.GetEncoding(Version, "latin1");

		handler.Configure();
	}
Esempio n. 8
0
    /// <summary>
    /// Execute the load operation
    /// </summary>
    /// <returns>The number of rows inserted.</returns>
    public int Load()
    {
      bool openedConnection = false;

      if (Connection == null)
        throw new InvalidOperationException(Resources.ConnectionNotSet);

      // next we open up the connetion if it is not already open
      if (connection.State != ConnectionState.Open)
      {
        openedConnection = true;
        connection.Open();
      }

      try
      {
        string sql = BuildSqlCommand();
        MySqlCommand cmd = new MySqlCommand(sql, Connection);
        cmd.CommandTimeout = Timeout;
        return cmd.ExecuteNonQuery();
      }
      finally
      {
        if (openedConnection)
          connection.Close();
      }
    }
Esempio n. 9
0
 public override void Commit()
 {
     if (conn == null || (conn.State != ConnectionState.Open && !conn.SoftClosed))
     throw new InvalidOperationException("Connection must be valid and open to commit transaction");
       if (!open)
     throw new InvalidOperationException("Transaction has already been committed or is not pending");
       MySqlCommand cmd = new MySqlCommand("COMMIT", conn);
       cmd.ExecuteNonQuery();
       open = false;
 }
Esempio n. 10
0
 public override void Rollback()
 {
     if (conn == null || (conn.State != ConnectionState.Open && !conn.SoftClosed))
     throw new InvalidOperationException("Connection must be valid and open to rollback transaction");
       if (!open)
     throw new InvalidOperationException("Transaction has already been rolled back or is not pending");
       MySqlCommand cmd = new MySqlCommand("ROLLBACK", conn);
       cmd.ExecuteNonQuery();
       open = false;
 }