示例#1
0
        public static string checkPaid()
        {
            bool paid = false;
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string          UserInfo        = ConfigurationManager.ConnectionStrings["KcGameOnSQL"].ConnectionString;
            MySqlDataReader paidReader      = null;
            MySqlCommand    mySQLCmd        = null;

            try
            {
                mySQLCmd             = new MySqlCommand("SELECT paymentKey,verifiedPaid FROM payTable WHERE paidDate = (SELECT MAX(paidDate) FROM payTable where userName = \'" + SessionVariables.UserName.ToLower() + "\' AND ActiveIndicator = \'TRUE\')", new MySqlConnection(UserInfo));
                mySQLCmd.CommandType = System.Data.CommandType.Text;
                mySQLCmd.Connection.Open();
                IAsyncResult result = mySQLCmd.BeginExecuteReader();
                paidReader = mySQLCmd.EndExecuteReader(result);
                result     = mySQLCmd.BeginExecuteReader();
                if (paidReader == null || !paidReader.HasRows)
                {
                    paid = false;
                    return(serializer.Serialize(paid));
                }
                else
                {
                    while (paidReader.Read())
                    {
                        if (paidReader["verifiedPaid"].ToString().Equals("Y"))
                        {
                            paid = true;
                        }
                    }
                    if (paid != true)
                    {
                        paid = checkPayPal();
                    }
                    return(serializer.Serialize(paid));
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                if (paidReader != null)
                {
                    paidReader.Close();
                }
                if (mySQLCmd != null)
                {
                    mySQLCmd.Connection.Close();
                }
            }
            paid = false;
            return(serializer.Serialize(paid));
        }
示例#2
0
        public async Task PollTest()
        {
            MySqlConnection connection;
            MySqlCommand    command = new MySqlCommand();
            MySqlDataReader reader;
            IAsyncResult    asyncResult;

            Console.WriteLine("程序已启动……");
            connection          = new MySqlConnection("Server=localhost; Database=Rainbow_Test_DB20180817; Uid=SkyUser; Pwd=Sky@4321;SslMode=none;");
            command.CommandText = "select * from agent ;";
            command.CommandType = CommandType.Text;
            command.Connection  = connection;
            connection.Open();

            var start = DateTime.Now;

            asyncResult = command.BeginExecuteReader(CommandBehavior.CloseConnection);
            while (!asyncResult.IsCompleted)
            {
                Console.WriteLine("正在取资料……");
                Thread.Sleep(10);
            }

            reader = command.EndExecuteReader(asyncResult);
            var count = 0;

            while (await reader.ReadAsync())
            {
                count++;
            }
            var end      = DateTime.Now;
            var timeSpan = end.Subtract(start);

            Console.WriteLine($"资料取出完成:{count.ToString()},总其用时{timeSpan.Milliseconds.ToString()}毫秒");
        }
        public void ExecuteReader()
        {
            if (Version < new Version(5, 0)) return;

            execSQL("CREATE TABLE test (id int)");
            execSQL("CREATE PROCEDURE spTest() BEGIN INSERT INTO test VALUES(1); " +
                "SELECT SLEEP(2); SELECT 'done'; END");

            MySqlCommand proc = new MySqlCommand("spTest", conn);
            proc.CommandType = CommandType.StoredProcedure;
            IAsyncResult iar = proc.BeginExecuteReader();
            int count = 0;
            while (!iar.IsCompleted)
            {
                count++;
                System.Threading.Thread.Sleep(20);
            }

            using (MySqlDataReader reader = proc.EndExecuteReader(iar))
            {
                Assert.IsNotNull(reader);
                Assert.IsTrue(count > 0, "count > 0");
                Assert.IsTrue(reader.Read(), "can read");
                Assert.IsTrue(reader.NextResult());
                Assert.IsTrue(reader.Read());
                Assert.AreEqual("done", reader.GetString(0));
                reader.Close();

                proc.CommandType = CommandType.Text;
                proc.CommandText = "SELECT COUNT(*) FROM test";
                object cnt = proc.ExecuteScalar();
                Assert.AreEqual(1, cnt);
            }
        }
示例#4
0
        /****   FUNÇÕES PARA GERIR OS TIPOS DE WEBSITES   *****/

        public ArrayList LIST_WEBSITE_TYPES()
        {
            MySqlCommand CMD_GET_WEBSITE_TYPES = new MySqlCommand("site_tvtuga_app_admin_users._SP_SELECT_WebsiteTipo", LigacaoDB);

            CMD_GET_WEBSITE_TYPES.CommandType = CommandType.StoredProcedure;

            LigacaoDB.Open();

            CMD_GET_WEBSITE_TYPES.Prepare();

            IAsyncResult Working_ListType = CMD_GET_WEBSITE_TYPES.BeginExecuteReader();

            Reader = CMD_GET_WEBSITE_TYPES.EndExecuteReader(Working_ListType);

            while (Reader.Read())
            {
                Tipos.Add(Reader["nome"].ToString());
            }

            Reader.Close();

            LigacaoDB.Close();

            return(Tipos);
        }
示例#5
0
文件: Main.cs 项目: quarkybit/mindpix
        private static ArrayList RunMySqlCommand(
            string commandText,
            string connectionString,
            int no_of_fields)
        {
            ArrayList rows = new ArrayList();

            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                try
                {
                    //Console.WriteLine("commandtext: " + commandText);
                    MySqlCommand command = new MySqlCommand(commandText, connection);

                    connection.Open();
                    IAsyncResult result = command.BeginExecuteReader();

                    int count = 0;
                    //DateTime start_time = DateTime.Now;
                    while (!result.IsCompleted)
                    {
                        count += 1;
                        //Console.WriteLine("Waiting ({0})", count);
                        System.Threading.Thread.Sleep(100);
                        //TimeSpan diff = DateTime.Now.Subtract(start_time);
                        //if (diff.TotalSeconds > 30) break;
                    }

                    MySqlDataReader query_result = command.EndExecuteReader(result);

                    while (query_result.Read())
                    {
                        ArrayList row = new ArrayList();
                        for (int i = 0; i < no_of_fields; i++)
                        {
                            row.Add(query_result.GetValue(i));
                        }
                        rows.Add(row);
                    }

                    connection.Close();
                }
                catch (MySqlException ex)
                {
                    Console.WriteLine("Error ({0}): {1}", ex.Number, ex.Message);
                    connection.Close();
                }
                catch (InvalidOperationException ex)
                {
                    Console.WriteLine("Error: {0}", ex.Message);
                    connection.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: {0}", ex.Message);
                    connection.Close();
                }
            }
            return(rows);
        }
    private IEnumerator DatabaseContains(string word, WVObject <bool?> result)
    {
        Debug.Log("Checking if db contains word " + word);

        using (MySqlCommand command = _connection.CreateCommand())
        {
            command.CommandText = "SELECT " + TABLE_WORD + " FROM " + TABLE_NAME +
                                  " WHERE " + TABLE_WORD + " = " + "'" + word + "'";

            System.IAsyncResult asyncResult = command.BeginExecuteReader();

            while (!asyncResult.IsCompleted)
            {
                yield return(null);
            }
            //Debug.Log(asyncResult.AsyncState);
            //Debug.Log(asyncResult.IsCompleted);
            try
            {
                MySqlDataReader data;
                using (data = command.EndExecuteReader(asyncResult))
                {
                    result.value = data.Read();
                    Debug.Log("DatabaseContains word '" + word + "': " + result.value.ToString());
                    //if (!data.IsClosed) data.Close();
                }
            }
            catch (System.InvalidOperationException e)
            {
                Debug.LogError(e.StackTrace);
                Debug.LogError(e.Message);
                Debug.Log(Connection.State.ToString());
            }
        }
    }
示例#7
0
        private void GET_TYPE_ID(string Tipo)
        {
            MySqlCommand CMD_GET_TYPE_ID = new MySqlCommand("site_tvtuga_app_admin_users._SP_SELECT_X_WebsiteTipo", LigacaoDB);

            CMD_GET_TYPE_ID.CommandType = CommandType.StoredProcedure;

            CMD_GET_TYPE_ID.Parameters.AddWithValue("_nome", Tipo);

            LigacaoDB.Open();

            CMD_GET_TYPE_ID.Prepare();

            IAsyncResult Working_GetTypeID = CMD_GET_TYPE_ID.BeginExecuteReader();

            Reader = CMD_GET_TYPE_ID.EndExecuteReader(Working_GetTypeID);

            while (Reader.Read())
            {
                //Tipo = Reader.GetString(0);

                Tipo = Reader["id"].ToString();
            }

            Reader.Close();

            TYPE_ID = Convert.ToInt32(Tipo);
        }
示例#8
0
        public bool Login_funcionario(string cpf, string senha)
        // checa o login dos funcionários
        {
            if (mConn.State == ConnectionState.Open)
            {
            }
            else
            {
                mConn.Open();
            }
            try
            {
                String       sql = "Select * from funcionario where cpf_func = @cpf and senha_func = @senha";
                MySqlCommand cmd = new MySqlCommand(sql, mConn);
                cmd.Parameters.AddWithValue("@cpf", cpf);
                cmd.Parameters.AddWithValue("@senha", senha);
                cmd.ExecuteNonQuery();

                cmd.BeginExecuteReader();
                dr = cmd.ExecuteReader();
                if (dr.HasRows)
                {
                    verify = true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                mConn.Close();
            }
            return(verify);
        }
示例#9
0
        /// <summary>
        /// <paramref name="cmd"/> 를 비동기 방식으로 실행하여, <see cref="Task{MySqlDataReader}"/>를 반환받습니다.
        /// 받환받은 DataReader는 꼭 Dispose() 해 주어야 Connection이 닫힙니다.
        /// </summary>
        /// <param name="db">DAAB의 MySQL 용 Database</param>
        /// <param name="cmd">실행할 <see cref="MySqlCommand"/> 인스턴스</param>
        /// <param name="parameters">Command Parameters</param>
        /// <returns><see cref="MySqlDataReader"/>를 결과로 반환하는 <see cref="Task"/></returns>
        public static Task <MySqlDataReader> ExecuteReaderAsync(this MySqlDatabase db, MySqlCommand cmd,
                                                                params IAdoParameter[] parameters)
        {
            cmd.ShouldNotBeNull("cmd");

            if (IsDebugEnabled)
            {
                log.Debug("MySqlCommand.ExecuteReader를 비동기 방식으로 실행합니다. CommandText=[{0}], Parameters=[{1}]",
                          cmd.CommandText, parameters.CollectionToString());
            }

            var newConnectionCreated = false;

            if (cmd.Connection == null)
            {
                cmd.Connection = db.CreateMySqlConnection(ref newConnectionCreated);
            }

            if (parameters != null)
            {
                AdoTool.SetParameterValues(db, cmd, parameters);
            }

            var commandBehavior = newConnectionCreated ? CommandBehavior.CloseConnection : CommandBehavior.Default;

            //! NOTE: FromAsync를 사용하지 못한 이유가 SqlCommand.BeginExecuteReader() 의 overloading이 많아서, 모호한 함수 호출 때문이다.
            //
            var ar = cmd.BeginExecuteReader(commandBehavior);

            return
                (Task <MySqlDataReader> .Factory
                 .StartNew(state => cmd.EndExecuteReader((IAsyncResult)state),
                           ar,
                           TaskCreationOptions.PreferFairness));
        }
示例#10
0
        private static void ReadAsync()
        {
            var conn = new MySqlConnection("Server=localhost;Database=sqlteacherdb;uid=demo;pwd=secret");

            conn.Open();
            _asyncQueryCmd = new MySqlCommand("SELECT mitarbeiternr, name, vorname FROM mitarbeiter;", conn);
            AsyncCmdEnded(_asyncQueryCmd.BeginExecuteReader());
        }
示例#11
0
        public void ThrowingExceptions()
        {
            MySqlCommand cmd = new MySqlCommand("SELECT xxx", Connection);
            IAsyncResult r   = cmd.BeginExecuteReader();
            Exception    ex  = Assert.Throws <MySqlException>(() => cmd.EndExecuteReader(r));

            Assert.Equal("Unknown column 'xxx' in 'field list'", ex.Message);
        }
        /// <summary>
        /// Checks when a client's characters were last cached, against a timestamp received from the client.
        /// If the client's timestamp doesn't match the one in the DB (meaning it was older or newer), information
        /// about all the characters is sent to the client.
        /// </summary>
        /// <param name="Timestamp">The timestamp received from the client.</param>
        public static void CheckCharacterTimestamp(string AccountName, LoginClient Client, DateTime Timestamp)
        {
            MySqlCommand Command = new MySqlCommand("SELECT AccountName, NumCharacters, Character1, Character2, Character3 " +
                                                    "FROM Accounts");

            Command.Connection = m_Connection;
            EndCheckCharacterID(Command.BeginExecuteReader(System.Data.CommandBehavior.Default));
        }
示例#13
0
    public async Task <string> SelectData()
    {
        return(await Task.Run <string>(() => {
            // 三秒間だけ待ってやる.
            Thread.Sleep(3000);
            const string result = "データー取得しました\n";

            MySqlConnection con = null;

            string conCmd =
                "Server=" + SERVER + ";" +
                "Database=" + DATABASE + ";" +
                "Userid=" + USERID + ";" +
                "Password="******";" +
                "Port=" + PORT + ";" +
                "CharSet=utf8;";

            try
            {
                Debug.Log("cmd : " + conCmd);
                con = new MySqlConnection(conCmd);
                Debug.Log("connection : " + con.State);
                con.Open();
            }
            catch (MySqlException ex)
            {
                Debug.Log(ex.ToString());
            }

            string selCmd = "SELECT * FROM " + TABLENAME + " LIMIT 0, 1200;";

            MySqlCommand cmd = new MySqlCommand(selCmd, con);

            IAsyncResult iAsync = cmd.BeginExecuteReader();

            while (!iAsync.IsCompleted)
            {
            }

            MySqlDataReader rdr = cmd.EndExecuteReader(iAsync);

            while (rdr.Read())
            {
                if (!rdr.IsDBNull(rdr.GetOrdinal("card_number")))
                {
                    Debug.Log("card number : " + rdr.GetString("card_number"));
                }
            }

            rdr.Close();
            rdr.Dispose();
            con.Close();
            con.Dispose();

            return result;
        }));
    }
        private void SelectMotionsFromMySQL()
        {
            MySqlConnection mysqlConn = null;

            try
            {
                string connString =
                    "server  =" + this.mysqlIpInputField.text + ";" +
                    "port    =" + this.mysqlPortInputField.text + ";" +
                    "database=" + MysqlSchemaName + ";" +
                    "userid  =" + this.mysqlUserInputField.text + ";" +
                    "password="******"SELECT * FROM " + MysqlSchemaName + "." + MysqlTableName + " WHERE recording_id=" + uniqueIdInputField.text;

                MySqlCommand mysqlCommand = new MySqlCommand(selectSql, mysqlConn);

                IAsyncResult iAsync = mysqlCommand.BeginExecuteReader();

                while (!iAsync.IsCompleted)
                {
                    Thread.Sleep(100);
                }

                MySqlDataReader mysqlDataReader = mysqlCommand.EndExecuteReader(iAsync);

                List <string> motionsDataList = new List <string>();

                while (mysqlDataReader.Read())
                {
                    motionsDataList.Add(mysqlDataReader.GetString("motion_data"));
                }

                mysqlDataReader.Close();
                mysqlCommand.Dispose();
                mysqlConn.Close();

                this.CreatePlayingTransformList(motionsDataList);

                this.isReading = false;
            }
            catch (Exception ex)
            {
                SIGVerseLogger.Error(ex.Message);
                SIGVerseLogger.Error(ex.StackTrace);

                if (mysqlConn != null)
                {
                    mysqlConn.Close();
                }
                Application.Quit();
            }
        }
    /// <summary>
    /// Gets a word and EmotionIdeal associated with it. This assumes that
    /// the database contains the word!
    /// </summary>
    /// <param name="word">Word to search for</param>
    /// <returns>WordAndEmoIdeal -- struct containing string and emotion ideal</returns>
    private IEnumerator GetWord(string word, WVObject <WordAndEmoIdeal> result)
    {
        Debug.Log("Getting word " + word + " from db");
        //WVObject<WordAndEmoIdeal> result = new WVObject<WordAndEmoIdeal>(word);

        WVObjectList_WordAndEmoIdeal.Add(result);

        WordAndEmoIdeal wordEmoIdeal = new WordAndEmoIdeal();

        using (MySqlCommand command = _connection.CreateCommand())
        {
            command.CommandText = "SELECT " + TABLE_WORD + ", " + TABLE_EMO_IDEAL + " FROM " + TABLE_NAME +
                                  " WHERE " + TABLE_WORD + " = " + "'" + word + "'";

            System.IAsyncResult asyncResult = command.BeginExecuteReader(System.Data.CommandBehavior.CloseConnection);

            Debug.Log("Connection before command: " + Connection.State.ToString());

            while (!asyncResult.IsCompleted)
            {
                yield return(null);
            }
            try
            {
                MySqlDataReader data;
                using (data = command.EndExecuteReader(asyncResult))
                {
                    //Debug.LogWarning("before data.Read()");
                    while (data.Read())
                    {
                        string w = (string)data[TABLE_WORD];
                        EmotionModel.EmotionIdeal emoIdeal = (EmotionModel.EmotionIdeal)
                                                             System.Enum.Parse(typeof(EmotionModel.EmotionIdeal),
                                                                               data[TABLE_EMO_IDEAL].ToString());

                        wordEmoIdeal.word    = w;
                        wordEmoIdeal.emoEnum = emoIdeal;

                        result.value = wordEmoIdeal;//at this point, since it's not null, we set it!
                        //Debug.LogWarning("reading data");
                    }
                    Debug.LogWarning("Data.isClosed = " + data.IsClosed.ToString());
                    //if (!data.IsClosed) data.Close();
                }
                //Debug.LogWarning("Data.isClosed AFTER using: " + data.IsClosed.ToString());

                //Debug.Log("Connection after everything: " + Connection.State.ToString());
            }
            catch (System.InvalidOperationException e)
            {
                Debug.LogError(e.StackTrace);
                Debug.LogError(e.Message);
                Debug.Log(Connection.State);
            }
        }
    }
示例#16
0
        public void ExecuteReader()
        {
            if (version < new Version(5, 0))
            {
                return;
            }

            execSQL("CREATE TABLE test (id int)");
            execSQL("CREATE PROCEDURE spTest() BEGIN INSERT INTO test VALUES(1); " +
                    "SELECT SLEEP(2); SELECT 'done'; END");

            MySqlDataReader reader = null;

            try
            {
                MySqlCommand proc = new MySqlCommand("spTest", conn);
                proc.CommandType = CommandType.StoredProcedure;
                IAsyncResult iar   = proc.BeginExecuteReader();
                int          count = 0;
                while (!iar.IsCompleted)
                {
                    count++;
                    System.Threading.Thread.Sleep(20);
                }

                reader = proc.EndExecuteReader(iar);
                Assert.IsNotNull(reader);
                Assert.IsTrue(count > 0, "count > 0");
                Assert.IsTrue(reader.Read(), "can read");
                Assert.IsTrue(reader.NextResult());
                Assert.IsTrue(reader.Read());
                Assert.AreEqual("done", reader.GetString(0));
                reader.Close();

                proc.CommandType = CommandType.Text;
                proc.CommandText = "SELECT COUNT(*) FROM test";
                object cnt = proc.ExecuteScalar();
                Assert.AreEqual(1, cnt);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
示例#17
0
        private string RetrieveSingleDataFromMySQL(MySqlCommand _cmd /*, string _request*/)
        {
            //_cmd.CommandText = _request;
            MySqlDataReader resultReader = _cmd.EndExecuteReader(_cmd.BeginExecuteReader()); //Executes query and acquire readeable result data

            if (resultReader.HasRows && resultReader.Read())                                 //If result contains something(in this case password), opens for reading and check if data is not null
            {
                string result = resultReader.GetString(0);
                resultReader.Close();
                return(result);
            }
            resultReader.Close();
            return("");
        }
示例#18
0
        public void ThrowingExceptions()
        {
            MySqlCommand cmd = new MySqlCommand("SELECT xxx", conn);
            IAsyncResult r   = cmd.BeginExecuteReader();

            try
            {
                using (MySqlDataReader reader = cmd.EndExecuteReader(r))
                {
                    Assert.Fail("EndExecuteReader should have thrown an exception");
                }
            }
            catch (MySqlException)
            {
            }
        }
示例#19
0
        public void ExecuteReader()
        {
            if (st.Version < new Version(5, 0))
            {
                return;
            }

            if (st.conn.State != ConnectionState.Open)
            {
                st.conn.Open();
            }

            st.execSQL("DROP TABLE IF EXISTS Test");
            st.execSQL("DROP PROCEDURE IF EXISTS spTest");
            st.execSQL("CREATE TABLE Test (id int)");
            st.execSQL("CREATE PROCEDURE spTest() BEGIN INSERT INTO Test VALUES(1); " +
                       "SELECT SLEEP(2); SELECT 'done'; END");

            MySqlCommand proc = new MySqlCommand("spTest", st.conn);

            proc.CommandType = CommandType.StoredProcedure;
            IAsyncResult iar   = proc.BeginExecuteReader();
            int          count = 0;

            while (!iar.IsCompleted)
            {
                count++;
                System.Threading.Thread.Sleep(20);
            }

            using (MySqlDataReader reader = proc.EndExecuteReader(iar))
            {
                Assert.NotNull(reader);
                Assert.True(count > 0, "count > 0");
                Assert.True(reader.Read(), "can read");
                Assert.True(reader.NextResult());
                Assert.True(reader.Read());
                Assert.Equal("done", reader.GetString(0));
                reader.Close();

                proc.CommandType = CommandType.Text;
                proc.CommandText = "SELECT COUNT(*) FROM Test";
                object cnt = proc.ExecuteScalar();
                Assert.Equal(1, Convert.ToInt32(cnt));
            }
        }
示例#20
0
        public void GET_USER_DB_ID(string Username)
        {
            try
            {
                MySqlCommand CMD_GET_USER_ID = new MySqlCommand();
                CMD_GET_USER_ID.Connection  = LigacaoDB.CONNECTION;
                CMD_GET_USER_ID.CommandText = "SELECT id FROM site_tvtuga_app_admin_users.admin_users WHERE username = '******'";

                LigacaoDB.OPEN_CONNECTION();

                CMD_GET_USER_ID.Prepare();

                IAsyncResult Working_GetUserID = CMD_GET_USER_ID.BeginExecuteReader();

                //while (!Working_GetUserID.IsCompleted)
                //{
                // Accções Adicionais
                //}

                Reader = CMD_GET_USER_ID.EndExecuteReader(Working_GetUserID);

                while (Reader.Read())
                {
                    for (int VALUE = 0; VALUE < Reader.FieldCount; VALUE++)
                    {
                        UserID = Convert.ToInt32(Reader.GetValue(VALUE));
                    }
                }

                Reader.Close();
            }

            catch (Exception EX)
            {
                MessageBox.Show("Ocorreu um erro de ligação. Verifique a sua configuração.\nDescrição do erro: \n\n " + EX.Message + "", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            finally
            {
                if (LigacaoDB.CONNECTION.State == ConnectionState.Open)
                {
                    LigacaoDB.CLOSE_CONNECTION();
                }
            }
        }
示例#21
0
        protected virtual IActiveOperation <TInternal> PrepareReaderOperation <TContext, TMySqlOperation, TOperation, TResult, TInternal>(TMySqlOperation operation, Func <TOperation, IAsyncResult, TInternal> createResultHandler, Func <MySqlCommand, TInternal, string> finalizer)
            where TContext : IQueryContext
            where TMySqlOperation : IMySqlQueryOperation <TContext, TInternal>, TOperation
            where TOperation : IQueryOperation, IOperation <TContext, TResult>
            where TResult : IQueryResult
            where TInternal : IQueryResultInternal, TResult
        {
            TInternal OperationResult;
            MySqlActiveOperation <TInternal> ActiveOperation;

            try
            {
                string QueryString = operation.GetCommandText();

                MySqlCommand Command = new MySqlCommand(QueryString, Connection);

                TraceCommand(Command);
                IAsyncResult Result = Command.BeginExecuteReader();

                OperationResult = createResultHandler(operation, Result);
                ActiveOperation = new MySqlActiveOperation <TInternal>(OperationResult, finalizer);
                ActiveOperationTable.Add(ActiveOperation, Command);
            }
#if TRACE
            catch (ApplicationException)
            {
                throw;
            }
#endif
            catch (MySqlException e)
            {
                TraceMySqlException(e);
                OperationResult = createResultHandler(operation, null);
                ActiveOperation = new MySqlActiveOperation <TInternal>(OperationResult);
            }
            catch (Exception e)
            {
                TraceException(e);
                OperationResult = createResultHandler(operation, null);
                ActiveOperation = new MySqlActiveOperation <TInternal>(OperationResult);
            }

            return(ActiveOperation);
        }
示例#22
0
    IEnumerator SelectData()
    {
        MySqlConnection con = null;

        string conCmd =
            "server=" + SERVER + ";" +
            "database=" + DATABASE + ";" +
            "userid=" + USERID + ";" +
            "port=" + PORT + ";" +
            "password="******"SELECT * FROM TABLENAME LIMIT 0, 1200;";

        MySqlCommand cmd = new MySqlCommand(selCmd, con);

        IAsyncResult iAsync = cmd.BeginExecuteReader();

        while (!iAsync.IsCompleted)
        {
            yield return(0);
        }

        MySqlDataReader rdr = cmd.EndExecuteReader(iAsync);

        while (rdr.Read())
        {
            if (!rdr.IsDBNull(rdr.GetOrdinal("ID")))
            {
                //Debug.Log ( "ID : " + rdr.GetString ("ID") );
            }
        }

        rdr.Close();
        rdr.Dispose();
        con.Close();
        con.Dispose();
    }
        /// <summary>
        /// Checks whether or not an account existed, and whether or not the password supplied was correct.
        /// </summary>
        /// <param name="AccountName">The name of the account.</param>
        /// <param name="Client">The client that supplied the account.</param>
        /// <param name="Hash">The hash of the password (with the username as a salt).</param>
        public static void CheckAccount(string AccountName, LoginClient Client, byte[] Hash)
        {
            if (m_Connection == null)
            {
                if (GlobalSettings.Default.CreateAccountsOnLogin == false)
                {
                    //TODO: Check if a flat file database exists, otherwise send an accountlogin failed packet.
                }
                else
                {
                    //TODO: Write account into flat file DB if it doesn't exist.
                }
            }

            //Gets the data from both rows (AccountName & Password)
            MySqlCommand Command = new MySqlCommand("SELECT AccountName, Password FROM Accounts");

            Command.Connection = m_Connection;
            EndCheckAccount(Command.BeginExecuteReader(System.Data.CommandBehavior.Default));
        }
示例#24
0
        public void ExecuteReaderAsyncTest()
        {
            using (var conn = new MySqlConnection(DefaultConnectionString))
                using (var cmd = new MySqlCommand(SQL_CUSTOMER_SELECT, conn)) {
                    conn.Open();

                    //! MySqlCommandAsync 를 참조하세요
                    //
                    var ar = cmd.BeginExecuteReader();

                    Thread.Sleep(1);

                    using (var reader = cmd.EndExecuteReader(ar)) {
                        var customers = reader.Map <Customer>(() => new Customer(), new TrimNameMapper());
                        customers.Count.Should().Be.GreaterThan(0);

                        customers.All(customer => customer.CompanyName.IsNotWhiteSpace()).Should().Be.True();
                    }
                }
        }
示例#25
0
        public void FILL_WEBSITE_DATA(string Nome)
        {
            try
            {
                GET_WEBSITE_ID(Nome);

                MySqlCommand CMD_GET_WEBSITE_DATA = new MySqlCommand("site_tvtuga_app_admin_users._SP_SELECT_X_Websites_Data", LigacaoDB);
                CMD_GET_WEBSITE_DATA.CommandType = CommandType.StoredProcedure;

                CMD_GET_WEBSITE_DATA.Parameters.AddWithValue("_nome", Nome);

                if (LigacaoDB.State == ConnectionState.Closed)
                {
                    LigacaoDB.Open();
                }

                CMD_GET_WEBSITE_DATA.Prepare();

                IAsyncResult Working_WebsiteData = CMD_GET_WEBSITE_DATA.BeginExecuteReader();

                Reader = CMD_GET_WEBSITE_DATA.EndExecuteReader(Working_WebsiteData);

                while (Reader.Read())
                {
                    Websites_Data.Add(Reader["WebsiteNome"].ToString());
                    Websites_Data.Add(Reader["WebsiteEndereco"].ToString());
                    Websites_Data.Add(Reader["TipoNome"].ToString());
                }
            }

            catch (Exception EX)
            {
                MessageBox.Show("Ocorreu um erro. Descrição do erro: \n\n " + EX.Message + "", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            finally
            {
                Reader.Close();
                LigacaoDB.Close();
            }
        }
示例#26
0
        // todo to ensure thread-safe
        // todo one handle can associate one dataReader at most
        public async Task <ILoadDataContext> Query(string sql, object key)
        {
            var cmd = new MySqlCommand(sql, Handle);

            cmd.Parameters.AddWithValue("1", key);

            var ret = await Task.Factory.FromAsync(cmd.BeginExecuteNonQuery(), (ar => cmd.EndExecuteNonQuery(ar)), TaskCreationOptions.None);

            var reader = await Task.Factory.FromAsync(cmd.BeginExecuteReader(), (ar => cmd.EndExecuteReader(ar)), TaskCreationOptions.None);

            if (!reader.Read())
            {
                cmd.Dispose();
                reader.Dispose();
                return(null);
            }

            return(new MysqlLoadDataContext()
            {
                Reader = reader,
                MysqlAdaptor = this,
            });
        }
 public void ThrowingExceptions()
 {
     MySqlCommand cmd = new MySqlCommand("SELECT xxx", conn);
     IAsyncResult r = cmd.BeginExecuteReader();
     try
     {
         using (MySqlDataReader reader = cmd.EndExecuteReader(r))
         {
             Assert.Fail("EndExecuteReader should have thrown an exception");
         }
     }
     catch (MySqlException)
     {
     }
 }