示例#1
0
    }//ActualizarDatos();

    /// <summary>
    /// Eliminar datos del usuario
    /// </summary>
    /// <param name="guid"></param>
    public void EliminarDatos()
    {
        string guidJson = LeerGuidJson();

        try
        {
            if (ComprobarGuid(guidJson))
            {
                conexion        = new MySqlConnection(cadenaConexion);
                cmd             = new MySqlCommand("Player_Delete", conexion);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@guidBorrado", GuidCargado);

                conexion.Open();
                cmd.ExecuteNonQuery();
                conexion.Close();

                File.Delete(rutaPath);
                File.Delete(rutaPath + ".meta");//Borrar al tener el .exe

                Publicar(Codes.UsuarioEliminado.ToString() + "///" + GuidCargado, "log");
            }
        }
        catch (MySqlException ex)
        {
            cmd.Cancel();
            conexion.Close();
            Publicar(GuidCargado + Codes.ErrorAlEliminar.ToString() + ex.ToString(), "excepcion");
        }
    }//EliminarDatos();
示例#2
0
    }//CargarDatosUsuario();

    /// <summary>
    /// Insertart datos del usuario
    /// </summary>
    /// <param name="guid">Clave principal del usuario</param>
    /// <param name="nombre">Nombre del usuario</param>
    /// <param name="monedas">Monedas en la cuenta</param>
    /// <param name="tiempo">Tiempo record del juego</param>
    public void InsertarDatos(string guid, string nombre, int monedas, string Minutos, string Segundos, int Partidas, int Ban, int Skin)
    {
        try
        {
            cmd             = new MySqlCommand("Player_Insert", conexion);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Guid", guid);
            cmd.Parameters.AddWithValue("@Nombre", nombre);
            cmd.Parameters.AddWithValue("@Monedas", monedas);
            cmd.Parameters.AddWithValue("@Minutos", Minutos);
            cmd.Parameters.AddWithValue("@Segundos", Segundos);
            cmd.Parameters.AddWithValue("@Partidas", Partidas);
            cmd.Parameters.AddWithValue("@Baneado", Ban);
            cmd.Parameters.AddWithValue("@Skin", Skin);

            conexion.Open();
            cmd.ExecuteNonQuery();
            conexion.Close();

            Publicar(Codes.UsuarioCreado.ToString() + "///" + guid + "///" + nombre, "log");
        }
        catch (MySqlException ex)
        {
            cmd.Cancel();
            conexion.Close();
            Publicar(guid + Codes.ErrorAlInsertar.ToString() + ex.ToString(), "excepcion");
        }
    }//InsertarDatos();
示例#3
0
    /// <summary>
    /// Obtener informacion del usuario
    /// </summary>
    public void CargarDatosUsuario(string guid)
    {
        try
        {
            query = "SELECT * FROM datosjugador WHERE Guid like '" + guid + "';";
            cmd   = new MySqlCommand(query, conexion);
            conexion.Open();
            cmd.ExecuteNonQuery();
            conexion.Close();

            adaptador = new MySqlDataAdapter(query, conexion);
            dt        = new DataTable();
            adaptador.Fill(dt);

            if (dt.Rows.Count > 0)
            {
                GuidCargado      = dt.Rows[0]["Guid"].ToString();
                NombreCargado    = dt.Rows[0]["Nombre"].ToString();
                MonedasCargadas  = int.Parse(dt.Rows[0]["Monedas"].ToString());
                MinutosCargados  = (dt.Rows[0]["Minutos"].ToString());
                SegundosCargados = (dt.Rows[0]["Segundos"].ToString());
                PartidasCargadas = int.Parse(dt.Rows[0]["Partidas"].ToString()); //Fatalba cargar las partidas
                BanCargado       = int.Parse(dt.Rows[0]["Baneado"].ToString());  //He cambiado a int la propiedad
                SkinCargada      = int.Parse(dt.Rows[0]["Skin"].ToString());
            }

            conexion.Close();
        }
        catch (Exception ex)
        {
            cmd.Cancel();
            conexion.Close();
            Publicar(GuidCargado + Codes.ErrorAlCargar.ToString() + ex.ToString(), "excepcion");
        }
    }//CargarDatosUsuario();
        public static async Task <bool> insertUser(Account user)
        {
            return(await Task.Run(() =>
            {
                bool resultFlag = false;
                if (connection.State != ConnectionState.Open)
                {
                    openConnection();
                }
                if (connection.State == ConnectionState.Open)
                {
                    var insertQuery = "INSERT INTO wypozyczalniaUzytkownicy(firstName,lastName,city,address,houseNumber,apartmentNumber,email,password) VALUES ('" + user.firstName + "','" + user.lastName + "','" + user.city + "','" + user.address + "','" + user.houseNumber + "','" + user.apartmentNumber + "','" + user.email + "','" + user.password + "');";
                    var result = new MySqlCommand(insertQuery, connection);
                    try
                    {
                        MySqlDataReader resultReader = result.ExecuteReader();
                        resultFlag = true;
                        resultReader.Close();
                    }
                    catch
                    {
                        resultFlag = false;
                    }
                    result.Cancel();
                    connection.Close();
                }

                return resultFlag;
            }));
        }
示例#5
0
        public void CancelSingleQuery()
        {
            if (Version < new Version(5, 0))
            {
                return;
            }

            // first we need a routine that will run for a bit
            execSQL(@"CREATE PROCEDURE spTest(duration INT) 
                BEGIN 
                    SELECT SLEEP(duration);
                END");

            MySqlCommand cmd = new MySqlCommand("spTest", conn);

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("duration", 10);

            // now we start execution of the command
            CommandInvokerDelegate d = new CommandInvokerDelegate(CommandRunner);

            d.BeginInvoke(cmd, null, null);

            // sleep 1 seconds
            Thread.Sleep(1000);

            // now cancel the command
            cmd.Cancel();
        }
        public static async Task <bool> insertCar(string brand, string model, int type, decimal odometer, string registrationNumber, int efficiency, int isDisabled, string imageUrl)
        {
            return(await Task.Run(() =>
            {
                bool resultFlag = false;
                if (connection.State != ConnectionState.Open)
                {
                    openConnection();
                }
                if (connection.State == ConnectionState.Open)
                {
                    var insertQuery = "INSERT INTO wypozyczalniaSamochody(brand, model, type, odometer, registrationNumber, efficiency, isDisabled, imageUrl) VALUES ('" + brand + "','" + model + "','" + type + "','" + odometer + "','" + registrationNumber + "','" + efficiency + "','" + isDisabled + "','" + imageUrl + "');";
                    var result = new MySqlCommand(insertQuery, connection);
                    try
                    {
                        MySqlDataReader resultReader = result.ExecuteReader();
                        resultFlag = true;
                        resultReader.Close();
                    }
                    catch
                    {
                        resultFlag = false;
                    }
                    result.Cancel();
                    connection.Close();
                }

                return resultFlag;
            }));
        }
示例#7
0
        public List <Dictionary <string, string> > ExecuteQuery(string query)
        {
            List <Dictionary <string, string> > results = new List <Dictionary <string, string> >();
            MySqlCommand    comm   = new MySqlCommand(query, _conn);
            MySqlDataReader reader = null;

            try
            {
                reader = comm.ExecuteReader();
            }
            catch (MySqlException exception)
            {
                throw new DBQExecutionFailException(exception.Code, exception.Number, exception.SqlState, exception.Message);
            }

            while (reader.Read())
            {
                results.Add(new Dictionary <string, string>());
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    results.Last().Add(reader.GetName(i), reader.IsDBNull(i) ? DatabaseModel.NullVal : reader.GetString(i));
                }
            }
            comm.Cancel();
            reader.Close();
            return(results);
        }
示例#8
0
        public void ExecuteReaderReturnsReaderAfterCancel()
        {
            execSQL("DROP TABLE IF EXISTS TableWithDateAsPrimaryKey");
            execSQL("DROP TABLE IF EXISTS TableWithStringAsPrimaryKey");
            createTable("CREATE TABLE TableWithDateAsPrimaryKey(PrimaryKey date NOT NULL, PRIMARY KEY  (PrimaryKey))", "InnoDB");
            createTable("CREATE TABLE TableWithStringAsPrimaryKey(PrimaryKey nvarchar(50) NOT NULL, PRIMARY KEY  (PrimaryKey))", "InnoDB");

            string connStr = GetConnectionString(true);

            using (MySqlConnection connection = new MySqlConnection(connStr))
            {
                connection.Open();
                MySqlCommand command         = new MySqlCommand("SELECT PrimaryKey FROM TableWithDateAsPrimaryKey", connection);
                IDataReader  reader          = command.ExecuteReader(CommandBehavior.KeyInfo);
                DataTable    dataTableSchema = reader.GetSchemaTable();
                command.Cancel();
                reader.Close();

                command = new MySqlCommand("SELECT PrimaryKey FROM TableWithStringAsPrimaryKey", connection);
                reader  = command.ExecuteReader(CommandBehavior.KeyInfo);
                Assert.IsNotNull(reader);

                dataTableSchema = reader.GetSchemaTable();
                Assert.AreEqual("PrimaryKey", dataTableSchema.Rows[0][dataTableSchema.Columns[0]]);

                reader.Close();
            }
        }
示例#9
0
        /// <summary>
        /// Verify if O.S informations in List<>WaitList are done already
        /// </summary>
        public static void CheckList()
        {
            LogWriteLine("-------------------Executing unfinished O.S vector-------------------");
            Conection.DeskOpen();
            MySqlCommand sqlcommand = new MySqlCommand("", Conection.DeskConection);

            //This method is basically the same thing than the SatisfactionSenderSeeker(). the only difference is that this method already have the os number.
            for (int i = 0; i < WaitList.Count; i++)
            {
                sqlcommand.CommandText = "SELECT stc_os1 FROM v11_mafra.OpOrdensServicoCabecalhos where cod_os1 = " + WaitList[i].Cod;
                try
                {
                    int getstate = Convert.ToInt32(sqlcommand.ExecuteScalar());
                    if (getstate == 83)
                    {
                        InformationOS aux = WaitList[i];
                        WaitList.Remove(WaitList[i]);
                        GreenSignal(aux, i);
                        System.Threading.Thread.Sleep(1000);
                    }
                }
                catch (Exception e)
                {
                    LogWriteLine("CODE 168 FAIL TO GET THE STATE OF O.S " + WaitList[i].Cod + " ERROR: " + e.Message);
                }
            }
            sqlcommand.Cancel();
            Conection.DeskConection.Close();
        }
示例#10
0
        public void CancelSelect()
        {
            if (version < new Version(5, 0)) return;

            execSQL("CREATE TABLE Test (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20))");
            for (int i=0; i < 10000; i++)
                execSQL("INSERT INTO Test VALUES (NULL, 'my string')");

            MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn);
            cmd.CommandTimeout = 0;
            int rows = 0;
            using (MySqlDataReader reader = cmd.ExecuteReader())
            {
                reader.Read();

                cmd.Cancel();

                try
                {
                    while (reader.Read())
                    {
                        rows++;
                    }
                }
                catch (Exception ex)
                {
                    Assert.Fail(ex.Message);
                }
            }
            Assert.IsTrue(rows < 10000);
        }
示例#11
0
        //Insert statement
        public static void InsertICMPRecord(IPHeader ipHeader, ICMPHeader icmpHeader)
        {
            String table_name = "ICMP_Packet";

            string timestamp = DateTime.Now.ToString();
            string source_ip = ipHeader.SourceAddress.ToString();
            string dest_ip   = ipHeader.DestinationAddress.ToString();

            // IPAddress 0 for host machine, 1 for external I.P.

            int    type         = icmpHeader.Type;
            int    code         = icmpHeader.Code;
            string time_to_live = ipHeader.TTL;

            string query = string.Format("Insert into {0} values( '{1}','{2}','{3}',{4},{5}, {[6});", table_name, timestamp, source_ip, dest_ip, type, code, time_to_live);

            Console.WriteLine(query);

            //open connection
            MySqlCommand cmd = new MySqlCommand(query, connection);

            cmd.Cancel();
            //Execute command
            cmd.ExecuteNonQueryAsync();
        }
示例#12
0
        public int admin_user_add(String id, String pw, String level)
        {
            int check = 0;

            try
            {
                MySqlCommand comm = new MySqlCommand();
                comm.Connection  = connection;
                comm.CommandText = "INSERT INTO user values(@id, @pw, 0, 'new', @level);";
                comm.Parameters.AddWithValue("@id", id);
                comm.Parameters.AddWithValue("@pw", pw);
                comm.Parameters.AddWithValue("@level", level);

                if (idcheck(id) == 0)
                {
                    comm.ExecuteNonQuery();
                    check = 1;
                }
                comm.Cancel();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return(check);
        }
示例#13
0
 /// <summary>
 /// 关闭数据库连接
 /// </summary>
 public static void CloseDataBase()
 {
     try
     {
         //销毁Commend
         if (_mysqlCommand != null)
         {
             _mysqlCommand.Cancel();
         }
         _mysqlCommand = null;
         //销毁Reader
         if (_mysqlReader != null)
         {
             _mysqlReader.Close();
         }
         _mysqlReader = null;
         //销毁Connection
         if (_mysqlConnection != null)
         {
             _mysqlConnection.Close();
         }
         _mysqlConnection = null;
         Console.WriteLine("成功关闭数据库");
     }
     catch (Exception e)
     {
         Console.WriteLine("关闭数据库出现问题" + e.Message);
         throw;
     }
 }
示例#14
0
        public void CancelSingleQuery()
        {
            // first we need a routine that will run for a bit
            executeSQL(@"CREATE PROCEDURE CancelSingleQuery(duration INT) 
        BEGIN 
          SELECT SLEEP(duration);
        END");

            MySqlCommand cmd = new MySqlCommand("CancelSingleQuery", Connection);

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("duration", 10);

            // now we start execution of the command
            CommandInvokerDelegate d = new CommandInvokerDelegate(CommandRunner);

            d.BeginInvoke(cmd, null, null);

            // sleep 1 seconds
            Thread.Sleep(1000);

            // now cancel the command
            cmd.Cancel();

            Assert.True(resetEvent.WaitOne(30 * 1000), "timeout");
        }
示例#15
0
        /// <summary>
        /// 执行非查询SQL语句
        /// </summary>
        /// <param name="sql">SQL语句</param>
        /// <param name="parameters">参数集合</param>
        /// <returns>受影响的记录数</returns>
        public override int ExecuteNoQuery(string sql, KdtParameterCollection parameters)
        {
            try
            {
                int effected = 0;

                // 执行SQL命令
                using (MySqlCommand cmd = new MySqlCommand(ReplaceSqlText(sql, parameters), _mySqlCn))
                {
                    InitCommand(cmd); // 初始化

                    // 赋值参数
                    var hasConvertParams = ConvertToSqlParameter(parameters);
                    foreach (var item in hasConvertParams)
                    {
                        cmd.Parameters.Add(item.Value);
                    }

                    effected = cmd.ExecuteNonQuery();

                    cmd.Cancel();
                    cmd.Dispose();
                }

                return(effected);
            }
            catch (Exception ex)
            {
                KdtLoger.Instance.Error(ex);
                throw new DataException(string.Format("执行非查询SQL语句错误,原因为:{0}", ex.Message));
            }
        }
示例#16
0
        /// <summary>
        /// 执行查询,返回查询结果的第一行第一列
        /// </summary>
        /// <typeparam name="T">返回值类型</typeparam>
        /// <param name="sql">SQL查询语句</param>
        /// <param name="parameters">参数集合</param>
        /// <returns>查询结果的第一行第一列</returns>
        public override T ExecuteScalar <T>(string sql, KdtParameterCollection parameters)
        {
            try
            {
                T value = default(T);

                // 执行SQL命令
                using (MySqlCommand cmd = new MySqlCommand(ReplaceSqlText(ReplaceSqlText(sql, parameters), parameters), _mySqlCn))
                {
                    InitCommand(cmd); // 初始化

                    // 赋值参数
                    var hasConvertParams = ConvertToSqlParameter(parameters);
                    foreach (var item in hasConvertParams)
                    {
                        cmd.Parameters.Add(item.Value);
                    }

                    value = cmd.ExecuteScalar().Convert <T>();

                    cmd.Cancel();
                    cmd.Dispose();
                }

                return(value);
            }
            catch (Exception ex)
            {
                KdtLoger.Instance.Error(ex);
                throw new DataException(string.Format("执行查询,返回查询结果的第一行第一列错误,原因为:{0}", ex.Message));
            }
        }
示例#17
0
        public static int ReadTableToInt(string query, string column)
        {
            int             result  = 0;
            MySqlConnection conn    = new MySqlConnection(Conf.Connstr);
            MySqlCommand    command = conn.CreateCommand();
            MySqlCommand    cmd     = new MySqlCommand(query, conn);

            try
            {
                conn.Open();
                MySqlDataReader reader = cmd.ExecuteReader(); //execure the reader
                while (reader.Read())
                {
                    result = reader.GetInt32(column);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                result = 0;
            }
            finally
            {
                cmd.Cancel();
                conn.Close();
                conn.Dispose();
            }
            return(result);
        }
示例#18
0
        /// <summary>
        /// Get a MembershipUsersCollection of MembershipUsers sorted by creation date.
        /// </summary>
        /// <param name="pageIndex">Current Page Index.</param>
        /// <param name="pageSize">Current Page Size.</param>
        /// <param name="membershipAppId">Membership ApplicationId.</param>
        /// <param name="connString">Membership database connection string.</param>
        /// <param name="totalUserCount">Returns the total users.</param>
        /// <remarks>This custom method requires the uspFindAllMembershipUsersSorted stored procedure to work properly.</remarks>
        /// <returns>A membershipUsersCollection sorted by creation date desc.</returns>
        private static MembershipUserCollection ListAllUsersSorted(int pageIndex, int pageSize, int membershipAppId, string connString, out int totalUserCount)
        {
            MySqlConnection          conn   = new MySqlConnection(connString);
            MembershipUserCollection users  = new MembershipUserCollection();
            MySqlDataReader          reader = null;

            totalUserCount = 0;

            try
            {
                conn.Open();
                totalUserCount = GetTotalUsers(membershipAppId, connString);
                if (totalUserCount <= 0)
                {
                    return(users);
                }

                MySqlCommand command = new MySqlCommand {
                    CommandType = CommandType.StoredProcedure, Connection = conn
                };
                command.Parameters.Add(new MySqlParameter("membershipAppId", membershipAppId));
                command.CommandText = "uspFindAllMembershipUsersSorted";

                reader = command.ExecuteReader();

                int counter    = 0;
                int startIndex = pageSize * pageIndex;
                int endIndex   = startIndex + pageSize - 1;

                while (reader.Read())
                {
                    if (counter >= startIndex)
                    {
                        MembershipUser u = GetUserFromReader(reader);
                        users.Add(u);
                    }

                    if (counter >= endIndex)
                    {
                        command.Cancel();
                        break;
                    }
                    counter++;
                }
            }
            catch (MySqlException)
            {
                // Handle exception.
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                conn.Close();
            }

            return(users);
        }
示例#19
0
        public int get_pwmiss(String id)
        {
            int    miss        = 0;
            string selectQuery = "Select password_miss from user where id=@id";

            try
            {
                using (MySqlCommand cmd = new MySqlCommand(selectQuery, connection))
                {
                    cmd.Parameters.AddWithValue("@id", id);
                    cmd.Prepare();

                    using (var reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            miss = int.Parse(reader.GetString(0));
                        }
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }
                    cmd.Cancel();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return(miss);
        }
示例#20
0
 public void StopRunSql()
 {
     if (_cmd != null)
     {
         _cmd.Cancel();
     }
 }
示例#21
0
 /// <summary>
 /// 获取封禁原因
 /// </summary>
 /// <param name="banPlayer">目标玩家</param>
 /// <returns></returns>
 public string GetBanReason(ServerPlayer banPlayer)
 {
     try
     {
         MySqlManager dbm = new MySqlManager();
         dbm.Connect();
         MySqlCommand cmd = dbm.command;
         cmd.CommandText = "select ban, banreason from users where username = @UserName";
         cmd.Parameters.AddWithValue("@UserName", banPlayer.Name);
         using (MySqlDataReader mdr = cmd.ExecuteReader())
         {
             if (mdr.Read())
             {
                 Ban       = mdr["ban"].ToString();
                 BanReason = mdr["banreason"].ToString();
             }
         }
         cmd.Cancel();
         if (Ban == "1")
         {
             return(BanReason);
         }
         else
         {
             return("");
         }
     }
     catch (Exception ex)
     {
         ErrorLog = ex.Message;
         return("");
     }
 }
示例#22
0
        public void User_update(List <String[]> get_user_list)
        {
            try
            {
                foreach (String[] user_ in get_user_list)
                {
                    String id      = user_[0];
                    String pw      = user_[1];
                    String pw_miss = user_[2];
                    String joinday = user_[3];
                    String level   = user_[4];

                    MySqlCommand comm = new MySqlCommand();
                    comm.Connection  = connection;
                    comm.CommandText = "update user set pw=@pw, password_miss=@pw_miss, joinday=@joinday, level=@level where id=@id;";
                    comm.Parameters.AddWithValue("@id", id);
                    comm.Parameters.AddWithValue("@pw", pw);
                    comm.Parameters.AddWithValue("@pw_miss", pw_miss);
                    comm.Parameters.AddWithValue("@joinday", joinday);
                    comm.Parameters.AddWithValue("@level", level);
                    comm.ExecuteNonQuery();
                    comm.Cancel();

                    Console.WriteLine("db:" + id + pw + pw_miss + joinday + level);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    public void CancelSingleQuery()
    {
      if (st.Version < new Version(5, 0)) return;

      // first we need a routine that will run for a bit
      st.execSQL(@"CREATE PROCEDURE spTest(duration INT) 
        BEGIN 
          SELECT SLEEP(duration);
        END");

      MySqlCommand cmd = new MySqlCommand("spTest", st.conn);
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.AddWithValue("duration", 10);

      // now we start execution of the command
      CommandInvokerDelegate d = new CommandInvokerDelegate(CommandRunner);
      d.BeginInvoke(cmd, null, null);

      // sleep 1 seconds
      Thread.Sleep(1000);

      // now cancel the command
      cmd.Cancel();

      resetEvent.WaitOne();
    }
示例#24
0
 private void Disconnect()
 {
     if (_con != null && _con.State == ConnectionState.Open)
     {
         _cmd.Cancel();
         _con.Close();
     }
 }
示例#25
0
        public void DoWork()
        {
            using (MySqlConnection conn = new MySqlConnection(GlobalUtils.TopSecret.MySqlCS))
                using (MySqlCommand command = new MySqlCommand())
                {
                    try
                    {
                        conn.Open();
                        //conn.StatisticsEnabled = true;
                        command.Connection = conn;
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine(e.Message);
                        return;
                    }
                    try
                    {
                        using (MySqlTransaction sqlTran = conn.BeginTransaction())
                        {
                            command.Transaction = sqlTran;
                            MySqlDataReader reader;

                            List <string> commands = GetCommands(com);
                            foreach (string c in commands)
                            {
                                command.CommandText = c;
                                using (reader = command.ExecuteReader())
                                {
                                    ShowResultSet(reader);
                                    while (reader.NextResult())
                                    {
                                        ShowResultSet(reader);
                                    }
                                }
                            }
                            //var stats = conn.RetrieveStatistics();
                            //using (TextWriter tw = new StreamWriter(path + ".stats"))
                            //{
                            //    tw.WriteLine("Execution time: {0} sec, rows selected: {1}, rows affected: {2}",
                            //                    Math.Round((double)(long)stats["ExecutionTime"] / 1000, 2),
                            //                    stats["SelectRows"],
                            //                    stats["IduRows"]);
                            //}
                        }
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine(e.Message);
                        if (command != null)
                        {
                            command.Cancel();
                        }
                    }
                }
        }
示例#26
0
        public static MySqlDataReader getGroupedPackets()
        {
            String       query = "SELECT TCP_Header.Source_IP, Source_Port, Time_To_Live, Count(SYN_Flag) as SYN, Count(ACK_Flag) as ACK, Count(FIN_Flag) as FIN, ICMP_Type, ICMP_Code from  TCP_Packet, ICMP_Packet where TCP_Packet.Source_IP = ICMP_Packet.Source_IP group by TCP_Packet.Source_IP";
            MySqlCommand cmd   = new MySqlCommand(query, connection);

            cmd.Cancel();
            MySqlDataReader read = cmd.ExecuteReader();

            return(read);
        }
示例#27
0
        public static MySqlDataReader getUDPPackets()
        {
            String       query = "SELECT * from  UDP_Packet";
            MySqlCommand cmd   = new MySqlCommand(query, connection);

            cmd.Cancel();
            MySqlDataReader read = cmd.ExecuteReader();

            return(read);
        }
示例#28
0
        private void bt_Delete_Click(object sender, RoutedEventArgs e)
        {
            int id = int.Parse(getReportid(lv_ReportList.SelectedValue.ToString()));

            lv_ReportList.Items.Clear();
            string          connstring = "server=localhost;database=loancalculator;uid=root;pwd=root";
            MySqlConnection conn       = new MySqlConnection(connstring);

            try
            {
                conn.Open();
                //MessageBox.Show("连接成功", "测试结果");
            }
            catch (MySqlException ex)
            {
                // MessageBox.Show(ex.Message);
            }
            MySqlCommand cmd = conn.CreateCommand();

            cmd.CommandText = "delete from peryearreport where sonid = " +
                              "(select sonid1 from annualreport where reportid = @reportid)";
            cmd.Parameters.AddWithValue("@reportid", id);
            cmd.ExecuteNonQuery();
            cmd.Cancel();
            cmd             = conn.CreateCommand();
            cmd.CommandText = "delete from peryearreport where sonid = " +
                              "(select sonid2 from annualreport where reportid = @reportid)";
            cmd.Parameters.AddWithValue("@reportid", id);
            cmd.ExecuteNonQuery();
            cmd.Cancel();
            cmd             = conn.CreateCommand();
            cmd.CommandText = "delete from peryearreport where sonid = " +
                              "(select sonid3 from annualreport where reportid = @reportid)";
            cmd.Parameters.AddWithValue("@reportid", id);
            cmd.ExecuteNonQuery();
            cmd.Cancel();
            cmd             = conn.CreateCommand();
            cmd.CommandText = "delete from annualreport where reportid = @reportid";
            cmd.Parameters.AddWithValue("@reportid", id);
            cmd.ExecuteNonQuery();
            cmd.Cancel();
            GetList();
        }
示例#29
0
        public override Data.DataSetStd Query(string sql, DBOParameterCollection dbp)
        {
            if (sqlcomm == null)
            {
                sqlcomm = new MySqlCommand(sql, this.conn);
                sqlcomm.CommandTimeout = 90;
            }
            else
            {
                sqlcomm.CommandText = sql;
            }
            //如果事務開啟,則使用事務的方式
            if (this._s == DBStatus.Begin_Trans)
            {
                sqlcomm.Transaction = this.tran;
            }


            DataSetStd ds = new DataSetStd();

            try
            {
                //如果有參數
                if (dbp != null)
                {
                    FillParametersToCommand(sqlcomm, dbp);
                }
                MySqlDataAdapter sqlAdapter = new MySqlDataAdapter(this.sqlcomm);
                sqlAdapter.Fill(ds);
            }
            catch (Exception ex)
            {
                sqlcomm.Cancel();
                throw ex;
            }
            finally
            {
                //sqlcomm.Cancel();
                //sqlcomm = null;
            }
            return(ds);
        }
示例#30
0
        private void RecordVisit(int id, ServerPlayer player)
        {
            var ipaddr = Netplay.Clients[id].Socket.GetRemoteAddress().GetIdentifier();

            QQAuth.MySqlManager sqlmanager = new QQAuth.MySqlManager();
            sqlmanager.Connect();
            MySqlCommand cmd = sqlmanager.command;

            cmd.CommandText = $"update users set lastIP = '{ipaddr}' where QQ = '{player.qqAuth.QQ}'";
            cmd.ExecuteNonQuery();
            cmd.Cancel();
        }
示例#31
0
        /// <summary>
        /// Check if employee belong to tecnical group (code 4)
        /// </summary>
        /// <returns></returns>
        private static int GetGroupCode()
        {
            Conection.DeskOpen();
            MySqlCommand sqlcommand = sqlcommand = new MySqlCommand("", Conection.DeskConection);

            sqlcommand.CommandText = "select gru_se1 from cadastrossenhasusuariosv11 where cod_se1 like '%" + nomfun + "%'";
            int getstate = Convert.ToInt32(sqlcommand.ExecuteScalar());

            sqlcommand.Cancel();
            Conection.DeskConection.Close();
            return(getstate);
        }
示例#32
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            string  connectionstring = null;
            string  rr            = null;
            Boolean found         = false;
            string  OLDdimXField  = null;
            string  OLDdimYField  = null;
            string  OLDpriceField = null;

            connectionstring = myConnection.connectionString();
            MySqlConnection cnn = new MySqlConnection(connectionstring);

            cnn.Open();
            MySqlCommand command = cnn.CreateCommand();

            command.Parameters.AddWithValue("@id", LoginWindow.id);

            command.CommandText = "SELECT * FROM products WHERE userid=@id";
            MySqlDataReader reader = command.ExecuteReader();

            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    rr = reader.GetString("name");
                    if (rr == nameField.Text)
                    {
                        OLDdimXField  = reader.GetFloat("dimX").ToString();
                        OLDdimYField  = reader.GetFloat("dimY").ToString();
                        OLDpriceField = reader.GetFloat("price").ToString();

                        float a = float.Parse(OLDdimXField) * float.Parse(OLDdimYField);

                        float b = float.Parse(OLDpriceField) / a;

                        float new_price = b * float.Parse(dimXField.Text) * float.Parse(dimYField.Text);

                        priceField.Text = new_price.ToString("0.00");
                        found           = true;
                    }
                }
                if (found == false)
                {
                    MessageBox.Show("This item is not in the database.Auto-Pricing can't work!");

                    reader.Close();
                    command.Cancel();
                }
            }

            cnn.Close();
        }
        public void CancelSelect()
        {
            if (Version < new Version(5, 0)) return;

              execSQL("CREATE TABLE Test (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20))");
              for (int i = 0; i < 1000; i++)
            execSQL("INSERT INTO Test VALUES (NULL, 'my string')");

              MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn);
              cmd.CommandTimeout = 0;
              int rows = 0;
              using (MySqlDataReader reader = cmd.ExecuteReader())
              {
            reader.Read();

            cmd.Cancel();

            while (true)
            {

              try
              {
            if (!reader.Read())
              break;
            rows++;
              }
              catch (MySqlException ex)
              {
            Assert.IsTrue(ex.Number == (int)MySqlErrorCode.QueryInterrupted);
            if (rows < 1000)
            {
              bool readOK = reader.Read();
              Assert.IsFalse(readOK);
            }
              }

            }
              }
              Assert.IsTrue(rows < 1000);
        }
        public void ExecuteReaderReturnsReaderAfterCancel()
        {
            execSQL("DROP TABLE IF EXISTS TableWithDateAsPrimaryKey");
            execSQL("DROP TABLE IF EXISTS TableWithStringAsPrimaryKey");
            createTable("CREATE TABLE TableWithDateAsPrimaryKey(PrimaryKey date NOT NULL, PRIMARY KEY  (PrimaryKey))", "InnoDB");
            createTable("CREATE TABLE TableWithStringAsPrimaryKey(PrimaryKey nvarchar(50) NOT NULL, PRIMARY KEY  (PrimaryKey))", "InnoDB");

            string connStr = GetConnectionString(true);
            using (MySqlConnection connection = new MySqlConnection(connStr))
            {
                connection.Open();
                MySqlCommand command = new MySqlCommand("SELECT PrimaryKey FROM TableWithDateAsPrimaryKey", connection);
                var reader = command.ExecuteReader(CommandBehavior.KeyInfo);
                //DataTable dataTableSchema = reader.GetSchemaTable();
                command.Cancel();
                reader.Close();

                command = new MySqlCommand("SELECT PrimaryKey FROM TableWithStringAsPrimaryKey", connection);
                reader = command.ExecuteReader(CommandBehavior.KeyInfo);
                Assert.IsNotNull(reader);

                //dataTableSchema = reader.GetSchemaTable();
                //Assert.AreEqual("PrimaryKey", dataTableSchema.Rows[0][dataTableSchema.Columns[0]]);

                reader.Close();
            }
        }
    public void ExecuteReaderReturnsReaderAfterCancel()
    {
      st.execSQL("DROP TABLE IF EXISTS TableWithDateAsPrimaryKey");
      st.execSQL("DROP TABLE IF EXISTS TableWithStringAsPrimaryKey");
      st.createTable("CREATE TABLE TableWithDateAsPrimaryKey(PrimaryKey date NOT NULL, PRIMARY KEY  (PrimaryKey))", "InnoDB");
      st.createTable("CREATE TABLE TableWithStringAsPrimaryKey(PrimaryKey nvarchar(50) NOT NULL, PRIMARY KEY  (PrimaryKey))", "InnoDB");

      string connStr = st.GetConnectionString(true);
      using (MySqlConnection connection = new MySqlConnection(connStr))
      {
        connection.Open();
        MySqlCommand command = new MySqlCommand("SELECT PrimaryKey FROM TableWithDateAsPrimaryKey", connection);
#if RT
        MySqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo);
        while (reader.Read()) ;
#else
        IDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo);
        DataTable dataTableSchema = reader.GetSchemaTable();
#endif
        command.Cancel();
        reader.Close();

        command = new MySqlCommand("SELECT PrimaryKey FROM TableWithStringAsPrimaryKey", connection);
        reader = command.ExecuteReader(CommandBehavior.KeyInfo);
        Assert.NotNull(reader);

#if RT
        while (reader.Read()) ;
        Assert.Equal("PrimaryKey", reader.GetName(0));
#else
        dataTableSchema = reader.GetSchemaTable();
        Assert.True("PrimaryKey" == (string)dataTableSchema.Rows[0][dataTableSchema.Columns[0]]);
#endif
        reader.Close();
      }
    }