Prepare() 공개 메소드

public Prepare ( ) : void
리턴 void
예제 #1
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string Connect = "Database=vlad_m;Data Source=192.168.27.79;User Id=vlad_m;charset=cp1251;Password=vlad19957";
                MySql.Data.MySqlClient.MySqlConnection myConnection = new MySql.Data.MySqlClient.MySqlConnection(Connect);
                MySql.Data.MySqlClient.MySqlCommand    myCommand    = new MySql.Data.MySqlClient.MySqlCommand();
                myConnection.Open();
                myCommand.Connection  = myConnection;
                myCommand.CommandText = string.Format("TRUNCATE TABLE result"); //запрос: если есть такой логин в таблице
                myCommand.Prepare();                                            //подготавливает строку
                myCommand.ExecuteNonQuery();                                    //выполняет запрос


                myCommand.CommandText = string.Format("INSERT INTO result SELECT ok.id_dog FROM ok,import_adress WHERE import_adress.id=ok.id_dog"); //запрос: если есть такой логин в таблице
                myCommand.Prepare();                                                                                                                 //подготавливает строку
                myCommand.ExecuteNonQuery();                                                                                                         //выполняет запрос

                myConnection.Close();
                MessageBox.Show("Result!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #2
0
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                string Connect = "Database=vlad_m;Data Source=192.168.27.79;User Id=vlad_m;charset=cp1251;Password=vlad19957";
                MySql.Data.MySqlClient.MySqlConnection myConnection = new MySql.Data.MySqlClient.MySqlConnection(Connect);
                MySql.Data.MySqlClient.MySqlCommand    myCommand    = new MySql.Data.MySqlClient.MySqlCommand();
                myConnection.Open();
                myCommand.Connection  = myConnection;
                myCommand.CommandText = string.Format("TRUNCATE TABLE export_double"); //запрос: если есть такой логин в таблице
                myCommand.Prepare();                                                   //подготавливает строку
                myCommand.ExecuteNonQuery();                                           //выполняет запрос

                // добавить проверку на уникальность
                myCommand.CommandText = string.Format("INSERT INTO export_double select id_dog, count(*) from import_double group by id_dog having count(*) > 1"); //запрос: если есть такой логин в таблице
                myCommand.Prepare();                                                                                                                               //подготавливает строку
                myCommand.ExecuteNonQuery();                                                                                                                       //выполняет запрос


                myCommand.CommandText = string.Format("select count(id_dog) from export_double"); //запрос: если есть такой логин в таблице
                myCommand.Prepare();                                                              //подготавливает строку
                myCommand.ExecuteNonQuery();                                                      //выполняет запрос
                int count = Convert.ToInt32(myCommand.ExecuteScalar());
                myConnection.Close();
                MessageBox.Show("Все export_double! " + count);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #3
0
 public void PutAnswerTest(int trueanswer, int answer, string[] answer_task)
 {
     try
     {
         new I18N.West.CP1250();
         string Connect = "Database=u0354899_diplom;Data Source=31.31.196.162;User Id=u0354899_vlad;Password=vlad19957;charset=utf8";
         MySql.Data.MySqlClient.MySqlConnection myConnection = new MySql.Data.MySqlClient.MySqlConnection(Connect);
         MySql.Data.MySqlClient.MySqlCommand    myCommand    = new MySql.Data.MySqlClient.MySqlCommand();
         myConnection.Open();
         myCommand.Connection  = myConnection;
         myCommand.CommandText = string.Format("INSERT INTO test_history (idstudent,idtest,false_quest,true_quest) VALUES ('{0}','{1}','{2}','{3}')", Student.idStudent, Student.idTest, trueanswer, answer); //запрос: если есть такой логин в таблице
         myCommand.Prepare();                                                                                                                                                                                 //подготавливает строку
         myCommand.ExecuteNonQuery();                                                                                                                                                                         //выполняет запрос
         int idTestH = (int)myCommand.LastInsertedId;                                                                                                                                                         //результат запроса
         if (Test.TheTaskIs)
         {
             foreach (string str in answer_task)
             {
                 myCommand.CommandText = string.Format("INSERT INTO task_history (idstudent,idtest,idhistory_quest,answer) VALUES ('{0}','{1}','{2}','{3}')", Student.idStudent, Student.idTest, idTestH, str); //запрос: если есть такой логин в таблице
                 myCommand.Prepare();                                                                                                                                                                           //подготавливает строку
                 myCommand.ExecuteNonQuery();                                                                                                                                                                   //выполняет запрос
             }
         }
         myConnection.Close();
     }
     catch (Exception e)
     {
         Console.Write(e.Message);
     }
 }
예제 #4
0
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                string Connect = "Database=vlad_m;Data Source=192.168.27.79;User Id=vlad_m;charset=cp1251;default command timeout = 240;Password=vlad19957";
                MySql.Data.MySqlClient.MySqlConnection myConnection = new MySql.Data.MySqlClient.MySqlConnection(Connect);
                MySql.Data.MySqlClient.MySqlCommand    myCommand    = new MySql.Data.MySqlClient.MySqlCommand();
                myConnection.Open();
                myCommand.Connection = myConnection;

                myCommand.CommandText = string.Format("TRUNCATE TABLE export_adress_gis");                                                                                                                         //запрос: если есть такой логин в таблице
                myCommand.Prepare();                                                                                                                                                                               //подготавливает строку
                myCommand.ExecuteNonQuery();                                                                                                                                                                       //выполняет запрос

                myCommand.CommandText = string.Format("INSERT INTO export_adress_gis SELECT result.id,import_adress.full_adr,import_adress.houseguid FROM result,import_adress WHERE result.id=import_adress.id"); //запрос: если есть такой логин в таблице
                myCommand.Prepare();                                                                                                                                                                               //подготавливает строку
                myCommand.ExecuteNonQuery();                                                                                                                                                                       //выполняет запрос


                myCommand.CommandText = string.Format("TRUNCATE TABLE export_with");                                                                                                                                          //запрос: если есть такой логин в таблице
                myCommand.Prepare();                                                                                                                                                                                          //подготавливает строку
                myCommand.ExecuteNonQuery();                                                                                                                                                                                  //выполняет запрос

                myCommand.CommandText = string.Format("INSERT INTO export_with SELECT import_with.A,import_with.B,import_with.C, import_with.DATA1,import_with.DATA2 FROM import_with,result WHERE result.id=import_with.A"); //запрос: если есть такой логин в таблице
                myCommand.Prepare();                                                                                                                                                                                          //подготавливает строку
                myCommand.ExecuteNonQuery();                                                                                                                                                                                  //выполняет запрос

                myConnection.Close();
                MessageBox.Show("Готово! Бегом в БД (export_adress_gis) :)");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #5
0
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                string Connect = "Database=vlad_m;Data Source=192.168.27.79;User Id=vlad_m;charset=cp1251;Password=vlad19957";
                MySql.Data.MySqlClient.MySqlConnection myConnection = new MySql.Data.MySqlClient.MySqlConnection(Connect);
                MySql.Data.MySqlClient.MySqlCommand    myCommand    = new MySql.Data.MySqlClient.MySqlCommand();
                myConnection.Open();
                myCommand.Connection  = myConnection;
                myCommand.CommandText = string.Format("TRUNCATE TABLE ok"); //запрос: если есть такой логин в таблице
                myCommand.Prepare();                                        //подготавливает строку
                myCommand.ExecuteNonQuery();                                //выполняет запрос

                // добавить проверку на уникальность
                myCommand.CommandText = string.Format("INSERT INTO ok SELECT id_gis,id_dog,status FROM import_project WHERE status='{0}'", textBox1.Text); //запрос: если есть такой логин в таблице
                myCommand.Prepare();                                                                                                                       //подготавливает строку
                myCommand.ExecuteNonQuery();                                                                                                               //выполняет запрос

                myConnection.Close();
                MessageBox.Show("Все OK!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #6
0
        private void button3_Click(object sender, EventArgs e)
        {
            List <String> ListNameId = new List <String>();

            try
            {
                string Connect = "Database=vlad_m;Data Source=192.168.27.79;User Id=vlad_m;charset=cp1251;default command timeout = 240;Password=vlad19957";
                MySql.Data.MySqlClient.MySqlConnection myConnection = new MySql.Data.MySqlClient.MySqlConnection(Connect);
                MySql.Data.MySqlClient.MySqlCommand    myCommand    = new MySql.Data.MySqlClient.MySqlCommand();
                myConnection.Open();
                myCommand.Connection = myConnection;

                myCommand.CommandText = string.Format("TRUNCATE TABLE export");                                                                                                                                                                                                                                                                                                                                                                                                                                        //запрос: если есть такой логин в таблице
                myCommand.Prepare();                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   //подготавливает строку
                myCommand.ExecuteNonQuery();                                                                                                                                                                                                                                                                                                                                                                                                                                                                           //выполняет запрос

                myCommand.CommandText = string.Format("INSERT INTO export SELECT final.A,final.PUBL_B,final.NUM_DOG_C,final.DAT_DOG_D,final.DAT_VST_E,final.F,final.G,final.H,final.FAMIL_NAME_R,final.IMEN_NAME_R,final.OTCH_NAME_R,final.POL_L,final.M,final.SNILS,final.O,final.P,final.Q,final.R,final.SROK1,final.СЛЕДУЮЩЕГОМЕСЯЦАЗАРАСЧЕТНЫМ,final.SROR2,final.СЛЕДУЮЩЕГОМЕСЯЦАЗАРАСЧЕТНЫМ2,final.DAT_NACH,final.НЕТ,final.DAT_OK,final.НЕТ2,final.id_gis FROM final,result WHERE final.NUM_DOG_C = result.id"); //запрос: если есть такой логин в таблице
                myCommand.Prepare();                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   //подготавливает строку
                myCommand.ExecuteNonQuery();                                                                                                                                                                                                                                                                                                                                                                                                                                                                           //выполняет запрос

                myCommand.CommandText = string.Format("update export, ok set export.id_gis = ok.id_gis where export.NUM_DOG_C = ok.id_dog");                                                                                                                                                                                                                                                                                                                                                                           //запрос: если есть такой логин в таблице
                myCommand.Prepare();                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   //подготавливает строку
                myCommand.ExecuteNonQuery();                                                                                                                                                                                                                                                                                                                                                                                                                                                                           //выполняет запрос



                myConnection.Close();
                MessageBox.Show("Готово! Бегом в БД :) export");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #7
0
        public ReportData getPatientReport(int patientID)
        {
            ReportData reportData = new ReportData();

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

                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = "SELECT * FROM patient where patientID=@pID";
                cmd.Prepare();
                cmd.Parameters.Add("@pID", MySqlDbType.Int32).Value = patientID;

                using (MySqlDataReader rdr = cmd.ExecuteReader())
                {

                    while (rdr.Read())
                    {
                        reportData.PatientData.PatientID = rdr.GetInt32("patientID");
                        reportData.PatientData.FirstName = rdr.GetString("firstName");
                        reportData.PatientData.LastName = rdr.GetString("lastName");
                        reportData.PatientData.DateAdmitted = rdr.GetDateTime("dateAdmitted");
                    }
                }

                //TODO new reach specific, fix later
                cmd.CommandText = "SELECT * FROM reach where patientID=@pID";
                cmd.Prepare();

                using (MySqlDataReader rdr = cmd.ExecuteReader())
                {

                    while (rdr.Read())
                    {
                        ExerciseData exerciseData = new ExerciseData();
                        exerciseData.ExerciseName = "reach";
                        exerciseData.PatientID = rdr.GetInt32("patientID");
                        exerciseData.EmployeeID = rdr.GetInt32("employeeID");
                        exerciseData.SessionID = rdr.GetInt32("sessionID");

                        //specific to reach
                        exerciseData.Hands = rdr.GetString("hands");
                        exerciseData.Angle = rdr.GetDouble("angle");
                        exerciseData.Date = rdr.GetDateTime("exerciseDate");
                        exerciseData.Time = rdr.GetDouble("time");

                        reportData.ExerciseDataList.Add(exerciseData);
                    }
                }

            }

            return reportData;

        }
예제 #8
0
 public async Task <string> GetAccountAuth(string login, string pass)
 {
     try
     {
         new I18N.West.CP1250();
         string Connect = "Database=u0354899_diplom;Data Source=31.31.196.162;User Id=u0354899_vlad;Password=vlad19957;charset=utf8";
         MySql.Data.MySqlClient.MySqlConnection myConnection = new MySql.Data.MySqlClient.MySqlConnection(Connect);
         MySql.Data.MySqlClient.MySqlCommand    myCommand    = new MySql.Data.MySqlClient.MySqlCommand();
         myConnection.Open();
         myCommand.Connection  = myConnection;
         myCommand.CommandText = string.Format("SELECT login FROM Student WHERE login='******' AND password='******' ", login, pass); //запрос: если есть такой логин в таблице
         myCommand.Prepare();                                                                                                   //подготавливает строку
         myCommand.ExecuteNonQuery();                                                                                           //выполняет запрос
         string LoginGlobal = (string)myCommand.ExecuteScalar();                                                                //результат запроса
         if (LoginGlobal == login)
         {
             myCommand.CommandText = string.Format("SELECT id FROM Student WHERE login='******'", login); //запрос: если есть такой логин в таблице
             myCommand.Prepare();                                                                      //подготавливает строку
             myCommand.ExecuteNonQuery();                                                              //выполняет запрос
             Student.idStudent = (int)myCommand.ExecuteScalar();                                       //результат запроса
             myConnection.Close();
             MainPage.AuthStudent = true;
             return(await Task <string> .FromResult("Вы зашли как студент"));
         }
         else
         {
             myCommand.CommandText = string.Format("SELECT login FROM teacher WHERE login='******' AND password='******' ", login, pass); //запрос: если есть такой логин в таблице
             myCommand.Prepare();                                                                                                   //подготавливает строку
             myCommand.ExecuteNonQuery();                                                                                           //выполняет запрос
             LoginGlobal = (string)myCommand.ExecuteScalar();                                                                       //результат запроса
             if (LoginGlobal == login)
             {
                 myConnection.Close();
                 MainPage.AuthTeacher = true;
                 return(await Task <string> .FromResult("Вы зашли как преподаватель"));
             }
             else
             {
                 myConnection.Close();
                 return(await Task <string> .FromResult("Логин или пароль не совпадают"));
             }
         }
     }
     catch (Exception ex)
     {
         return(await Task <string> .FromResult(ex.Message));
     }
 }
예제 #9
0
        public bool SalvarFornecedor(Fornecedor f)
        {
            try
            {
                String insertDados = "INSERT INTO fornecedor(nome, contato, razaosocial, cnpj, " +
                                     "logradouro, bairro, cidade, estado, cep, complemento) " +
                                     "VALUES (@nome, @contato, @razaosocial, @cnpj, @logradouro, @bairro, @cidade, @estado, @cep, @complemento);";
                conn = new MySqlConnection(connectionString);
                conn.Open();
                MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(insertDados, conn);
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("nome", f.nome));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("contato", f.contato));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("razaosocial", f.razaoSocial));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("cnpj", f.cnpj));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("logradouro", f.logradouro));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("bairro", f.bairro));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("cidade", f.cidade));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("estado", f.estado));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("cep", f.cep));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("complemento", f.complemento));

                cmd.Prepare();
                cmd.ExecuteNonQuery();
                conn.Close();

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro ou cadastrar cliente, verifique a conexão com o banco de dados: " + ex.ToString());
                return(false);
            }
        }
        public void DeleteCategorie(int categorie_id)
        {
            try
            {
                conn.Open();

                string insertString = @"delete from categorie where categorie_Id=@categorie_id";
                MySqlCommand cmd = new MySqlCommand(insertString, conn);
                MySqlParameter sportParam = new MySqlParameter("@categorie_id", MySqlDbType.Int32);

                sportParam.Value = categorie_id;

                cmd.Parameters.Add(sportParam);

                cmd.Prepare();

                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                Console.Write("categorie niet verwijderd: " + e);
                throw e;
            }
            finally
            {
                conn.Close();
            }
        }
예제 #11
0
        public bool SalvarVenda(Vendas v)
        {
            try
            {
                conn = new MySqlConnection(connectionString);

                String insertDados = "INSERT INTO vendas(nome, precounidade, quantidade, total)" +
                                     " VALUES (@nome, @precoUnidade, @quantidade, @total);";

                conn.Open();

                MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(insertDados, conn);
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("nome", v.nome));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("precounidade", v.precoUnidade));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("quantidade", v.quantidade));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("total", v.total));

                cmd.Prepare();
                cmd.ExecuteNonQuery();

                conn.Close();
                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro ao adicionar o produto: " + ex.ToString());
                return(false);
            }
        }
예제 #12
0
        public bool SalvarCliente(Clientes c)
        {
            try
            {
                conn = new MySqlConnection(connectionString);
                String insertDados = "INSERT INTO cliente(nome, datanascimento, celular, " +
                                     "cidade, logradouro, bairro, sexo, cpf, telfixo, cep, uf, complemento) " +
                                     "VALUES (@nome, @datanascimento, @celular, @cidade, @logradouro, " +
                                     "@bairro, @sexo, @cpf, @telfixo, @cep, @uf, @complemento);";
                conn.Open();
                MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(insertDados, conn);
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("nome", c.nome));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("datanascimento", c.dataNascimento));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("celular", c.celular));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("cidade", c.cidade));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("logradouro", c.logradouro));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("sexo", c.sexo));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("cpf", c.cpf));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("telfixo", c.telfixo));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("cep", c.cep));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("uf", c.uf));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("complemento", c.complemento));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("bairro", c.bairro));

                cmd.Prepare();
                cmd.ExecuteNonQuery();
                conn.Close();
                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro ao cadastrar o cliente, verifique a conexão com o banco de dados: " + ex.ToString());
                return(false);
            }
        }
예제 #13
0
        public bool SalvarProduto(Produto p)
        {
            try
            {
                conn = new MySqlConnection(connectionString);

                String insertDados = "INSERT INTO produto(nome, quantidade, descricao, precovenda, precocusto, modelo)" +
                                     " VALUES (@nome, @quantidade, @descricao, @precovenda, @precocusto, @modelo);";

                conn.Open();

                MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(insertDados, conn);
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("nome", p.nome));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("quantidade", p.quantidade));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("descricao", p.descricao));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("precovenda", p.precoVenda));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("precocusto", p.precoCusto));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("modelo", p.modelo));

                cmd.Prepare();
                cmd.ExecuteNonQuery();

                conn.Close();
                return(true);
            }catch (Exception ex)
            {
                MessageBox.Show("Erro ao salvar o produto: " + ex.ToString());
                return(false);
            }
        }
        public bool AtualizaFornecedor(Fornecedor f)
        {
            try
            {
                conn = new MySqlConnection(connectionString);

                String query = "UPDATE fornecedor SET nome=@nome, contato=@contato, razaoSocial=@razaoSocial," +
                               "cnpj=@cnpj, logradouro=@logradouro, bairro=@bairro, cidade=@cidade, estado=@estado, " +
                               "estado=estado, cep=@cep, complemento=@complemento WHERE id=@id;";

                conn.Open();
                MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(query, conn);
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("id", f.id_fornecedor));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("nome", f.nome));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("contato", f.contato));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("razaosocial", f.razaoSocial));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("cnpj", f.cnpj));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("logradouro", f.logradouro));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("bairro", f.bairro));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("cidade", f.cidade));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("estado", f.estado));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("cep", f.cep));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("complemento", f.complemento));

                cmd.Prepare();
                cmd.ExecuteNonQuery();
                conn.Close();
                return(true);
            }
            catch (Exception e)
            {
                MessageBox.Show("Erro ao atualizar o cliente: " + e.ToString());
                return(false);
            }
        }
예제 #15
0
        private void get_1k_resule(String Connection)
        {
            MySql.Data.MySqlClient.MySqlConnection conn;
            MySql.Data.MySqlClient.MySqlCommand    cmd;

            conn = new MySql.Data.MySqlClient.MySqlConnection();
            cmd  = new MySql.Data.MySqlClient.MySqlCommand();

            conn.ConnectionString = Connection;

            try
            {
                conn.Open();
                cmd.Connection = conn;

                cmd.CommandText = "SELECT * FROM `laneheartbeat`;";
                cmd.Prepare();

                MySqlDataAdapter sda = new MySqlDataAdapter("SELECT * FROM `laneheartbeat` LIMIT 500", conn);

                Log_Textblock.Text = cmd.ExecuteScalar().ToString();
                DataSet ds = new DataSet();
                ds.Clear();
                DataTable dt = new DataTable();
                sda.Fill(ds, "dt");
                Result_DataGrid.DataContext = ds;
            }

            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                MessageBox.Show("Error " + ex.Number + " has occurred: " + ex.Message,
                                "Error");
            }
        }
예제 #16
0
        public void SalvarViagem(Viagem v)
        {
            try
            {
                MySqlConnection conn = new ConexaoBancoMySQL().getConnection();
                conn = new MySqlConnection(connectionString);
                String insertDados = "INSERT INTO viagem(id_motorista, id_veiculo, id_cidade_destino, id_cidade_origem, dta_saida, km_cidade_origem, passageiro_viagem)" +
                                     "VALUES (?, ?, ?, ?, ?, ?, ?);";
                conn.Open();
                MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(insertDados, conn);
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("id_motorista", v.Id_motorista));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("id_veiculo", v.Id_veiculo));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("id_cidade_destino", v.Id_cidadeDestino));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("id_cidade_origem", v.Id_cidadeSaida));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("dta_saida", v.DtaSaida));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("km_cidade_origem", v.KmSaida));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("passageiro_viagem", v.passageiro));



                cmd.Prepare();

                cmd.ExecuteNonQuery();

                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro ao cadastrar a viagem, verifique a conexão com o banco de dados: " + ex.ToString());
            }
        }
예제 #17
0
        public void BaixarRelatorio(ManutencaoRelatorio m)
        {
            try
            {
                MySqlConnection conn = new ConexaoBancoMySQL().getConnection();
                conn = new MySqlConnection(connectionString);
                String insertDados = "UPDATE relatorio SET pendente_status = 'S',  observacaoBaixa = @observacaoBaixa,  requisito_correcao = @reqCorrecao  WHERE id_relatorio = @id_relatorio";
                conn.Open();
                MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(insertDados, conn);

                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("observacaoBaixa", m.ObservacaoBaixa));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("reqCorrecao", m.RequisitoCorrecao));

                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("id_relatorio", m.Id_relatorio));


                cmd.Prepare();

                cmd.ExecuteNonQuery();

                conn.Close();
                MessageBox.Show("Relatorio Baixado com sucesso!");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro ao cadastrar o usuario, verifique a conexão com o banco de dados: " + ex.ToString());
            }
        }
        /// <summary>
        /// Inserts solutions into the database table all_slutions using a prepared statement
        /// </summary>
        /// <param name="slns"> the solutions to be inserted</param>
        public void insertIntoAllSolutions(IEnumerable <ISolution> slns)
        {
            // get the connection object (The using statement handles closing of the connection no need to handle it separately)
            using (var dbcon = new DBConnection(ConnectionRetriever).Instance())
            {
                if (dbcon.IsConnect())
                {
                    // create the command
                    using (var cmd = new MySql.Data.MySqlClient.MySqlCommand())
                    {
                        cmd.Connection = dbcon.Connection;
                        // the insert statement
                        cmd.CommandText = @"INSERT INTO all_solutions(solution_id,batch_id,serialized_data) 
                                            VALUES(@slnid,@batchid,@slr)";
                        cmd.Prepare();

                        cmd.Parameters.Add(new MySqlParameter("@slnid", MySqlDbType.Int32));
                        cmd.Parameters.Add(new MySqlParameter("@batchid", MySqlDbType.Int32));
                        cmd.Parameters.Add(new MySqlParameter("@slr", MySqlDbType.JSON));
                        foreach (var sln in slns)
                        {
                            cmd.Parameters["@slnid"].Value   = sln.solutionid;
                            cmd.Parameters["@batchid"].Value = sln.batchid;
                            cmd.Parameters["@slr"].Value     = JsonConvert.SerializeObject(sln);

                            cmd.ExecuteNonQuery();
                            // returns each object one at a time
                            // the returned object can then be used by accesing the iterator defined in the calling method
                            //yield return sln;
                        }
                    }
                }
            }
        }
예제 #19
0
        public static ArrayList buscarPendentes(Emprestimo emprestimo)
        {
            ArrayList emprestimos = new ArrayList();

            MySqlCommand cmd;

            string sql = "SELECT * FROM " + TABELA
                    + " WHERE entregue = false;";

                // Associação do comando à conexão.
                cmd = new MySqlCommand(sql,
                    BancoDados.recuperarConexao());

                cmd.Prepare();

                // Execução da sentença SQL, com dados de retorno
                // associados a um objeto para posterior leitura.
                MySqlDataReader leitor = cmd.ExecuteReader();

            while (leitor.Read())
            {

                emprestimos.Add(
                    new Emprestimo(int.Parse(leitor["id"].ToString()), DateTime.Parse(leitor["dataemprestimo"].ToString()),
                        bool.Parse(leitor["entregue"].ToString()),int.Parse(leitor["fk_destinatario"].ToString()), int.Parse(leitor["fk_item"].ToString())));
            }

            leitor.Close();

            return emprestimos;
        }
예제 #20
0
        public void SalvarUsuario(Usuario u)
        {
            try
            {
                MySqlConnection conn = new ConexaoBancoMySQL().getConnection();
                conn = new MySqlConnection(connectionString);
                String insertDados = "INSERT INTO cadastro_usuario(nome_usuario, senha_usuario, ativo)" +
                                     "VALUES (?, MD5(?), ?);";
                conn.Open();
                MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(insertDados, conn);
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("nome", u.Nome));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("senha", u.Senha));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("ativo", u.Ativo));

                cmd.Prepare();

                cmd.ExecuteNonQuery();

                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro ao cadastrar o usuario, verifique a conexão com o banco de dados: " + ex.ToString());
            }
        }
예제 #21
0
        public void Salvar(Contato contato)
        {
            try
            {
                MySqlConnection conn = new ConexaoBancoMySql().getConnection();
                conn = new MySqlConnection(connectionString);
                String insertDados = "INSERT INTO contato(nome, telefone)" +
                                     "VALUES (?,?);";
                conn.Open();
                MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(insertDados, conn);
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("nome", contato.nome));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("telefone", contato.telefone));


                cmd.Prepare();

                cmd.ExecuteNonQuery();

                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro ao cadastrar contato, verifique a conexão com o banco de dados: " + ex.ToString());
            }
        }
        public static void setSession(string userid)
        {
            LoginInfo.UserID = userid;
            LoginInfo.inTime = DateTime.Now;
            LoginInfo.computer_name = Environment.MachineName;
            LoginInfo.ipAddress = Dns.GetHostAddresses(Environment.MachineName)[0].ToString();

            DBConnector dbcon = new DBConnector();
            dbcon.openConnection();

            MySqlCommand cmd = new MySqlCommand();
            cmd.CommandText = "INSERT INTO login_session (in_time, computer_name, ip_address, user_iduser) VALUES ('" + LoginInfo.inTime.ToString("yyyy-MM-dd HH:mm:ss") + "', N'" + LoginInfo.computer_name + "', '" + LoginInfo.ipAddress + "', "+int.Parse(LoginInfo.UserID)+")";
            cmd.Connection = dbcon.connection;
            cmd.Prepare();
            cmd.ExecuteNonQuery();

            cmd.CommandText = "SELECT * FROM login_session ORDER BY idlogin_session DESC LIMIT 1";
            cmd.Connection = dbcon.connection;

            MySqlDataReader reader = cmd.ExecuteReader();

            if (reader.Read())
            {
                LoginInfo.sessionID = int.Parse(reader.GetString(0));
                //Console.Write(LoginInfo.sessionID);
            }

            dbcon.closeConnection();
        }
        public void addEntry(TrackingEntry entry)
        {
            MySqlCommand cmd = new MySqlCommand();
            cmd.Connection = connection;
            cmd.CommandText = "INSERT INTO tracking_entry VALUES (NULL, @taggerID, @type, @isTagged,"
                + " @taggerName, @entryDate, @tagNumber, @species, @city, @state, @country,"
                + " @longitude, @latitude, @temperature, @precipitation, @windSpeed,"
                + " @windDirection);";
            cmd.Prepare();

            cmd.Parameters.AddWithValue("@taggerID", entry.taggerID);
            cmd.Parameters.AddWithValue("@type", entry.type);
            cmd.Parameters.AddWithValue("@isTagged", entry.isTagged);
            cmd.Parameters.AddWithValue("@taggerName", entry.taggerName);
            cmd.Parameters.AddWithValue("@entryDate", entry.entryDate);
            cmd.Parameters.AddWithValue("@tagNumber", entry.tagNumber);
            cmd.Parameters.AddWithValue("@species", entry.species);
            cmd.Parameters.AddWithValue("@city", entry.city);
            cmd.Parameters.AddWithValue("@state", entry.state);
            cmd.Parameters.AddWithValue("@country", entry.country);
            cmd.Parameters.AddWithValue("@longitude", entry.longitude);
            cmd.Parameters.AddWithValue("@latitude", entry.latitude);
            cmd.Parameters.AddWithValue("@temperature", entry.temperature);
            cmd.Parameters.AddWithValue("@precipitation", entry.precipitation);
            cmd.Parameters.AddWithValue("@windSpeed", entry.windSpeed);
            cmd.Parameters.AddWithValue("@windDirection", entry.windDirection);

            cmd.ExecuteNonQuery();
        }
예제 #24
0
        public static bool Delete(int id)
        {
            try
            {
                String delete_sql          = "DELETE FROM " + TABLE_NAME + " WHERE ID=@id";
                //Sql command
                sql_command                = new MySqlCommand();
                sql_command.Connection     = (MySqlConnection)database.OpenConnection();
                sql_command.CommandText    = delete_sql;
                sql_command.Parameters.AddWithValue("@id", id);
                sql_command.Prepare();

                //execute command
                database.Update(sql_command);

                return true;
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                CloseDatabaseConnection();
            }
        }
예제 #25
0
        public MailSession()
        {
            string cs = @"server=localhost;userid=timetracker;password=DdCyzpALrxndc6BY;database=timetracker";

            MySqlConnection connect = null;
            MySqlDataReader reader = null;

            try {
                connect = new MySqlConnection (cs);
                connect.Open ();

                MySqlCommand cmd = new MySqlCommand();
                cmd.CommandText = "SELECT * FROM `email`";
                cmd.Prepare();
                cmd.ExecuteNonQuery();

                reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    //Console.WriteLine(reader.GetInt32(0) + ": " + reader.GetString(1));
                }

            } catch (Exception ex) {
            } finally {
                if (connect != null)
                {
                    connect.Close();
                }
            }
        }
        public static bool addPassport(Passport p)
        {
            DBConnector dbcon = new DBConnector();

            //try
            //{
            if (dbcon.openConnection())
            {
                MySqlCommand cmd = new MySqlCommand();
                cmd.CommandText = "INSERT INTO passport (rank, post, passport_no, place_of_issue, date_of_issue, date_of_renewal, status, employee_idemployee) VALUES (N'" + p.rank + "', N'" + p.post + "', N'" + p.number + "', N'" + p.place_of_issue + "', '" + p.getdate_of_issue().ToString("yyyy-MM-dd") + "', '" + p.getdate_of_renewal().ToString("yyyy-MM-dd") + "', " + p.status + ", " + Employee.employee_id + ")";
                cmd.Connection = dbcon.connection;
                cmd.Prepare();
                cmd.ExecuteNonQuery();

                dbcon.closeConnection();
                return true;
            }
            else
            {
                dbcon.closeConnection();
                return false;
            }

            //}
            //catch (MySqlException e)
            //{
            //int errorcode = e.Number;
            //dbcon.closeConnection();
            //return false;
            //}
        }
예제 #27
0
        public bool AtualizaProduto(Produto p)
        {
            try
            {
                conn = new MySqlConnection(connectionString);

                String query = "UPDATE produto SET modelo=@modelo, nome=@nome," +
                               " quantidade=@quantidade, precocusto=@precoCusto, precovenda=@precoVenda," +
                               "descricao=@descricao WHERE id=@id;";

                conn.Open();
                MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(query, conn);
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("id", p.idProduto));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("modelo", p.modelo));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("nome", p.nome));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("quantidade", p.quantidade));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("precocusto", p.precoCusto));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("precovenda", p.precoVenda));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("descricao", p.descricao));

                cmd.Prepare();
                cmd.ExecuteNonQuery();
                conn.Close();
                return(true);
            }
            catch (Exception e)
            {
                MessageBox.Show("Erro ao atualizar o produto: " + e.ToString());
                return(false);
            }
        }
        public void AnnulerenBestelling(int bestellingscode)
        {
            try
            {
                conn.Open();

                string insertString = @"UPDATE factuur " +
                                        "SET status=@status " +
                                         "WHERE factuur_code=@factuur_code";

                MySqlCommand cmd = new MySqlCommand(insertString, conn);
                MySqlParameter bestellingscodeParam = new MySqlParameter("@factuur_code", MySqlDbType.Int32);
                MySqlParameter statusParam = new MySqlParameter("@status", MySqlDbType.Enum);

                bestellingscodeParam.Value = bestellingscode;
                statusParam.Value = "Geannulleerd";

                cmd.Parameters.Add(bestellingscodeParam);
                cmd.Parameters.Add(statusParam);

                cmd.Prepare();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                Console.Write("Updaten bestelling niet gelukt: " + e);
                throw e;
            }
            finally
            {
                conn.Close();
            }
        }
예제 #29
0
        private void buttonCadastrar_Click(object sender, EventArgs e)
        {
            MySqlConnection conn = null;

            try
            {
                conn = Conexao.getConexao();
                MySqlCommand cmd = new MySqlCommand("call cadastra_pizza(@nome, @tamanho, @preco)", conn);
                cmd.Prepare();
                cmd.Parameters.AddWithValue("@nome", this.txt_nome.Text);
                cmd.Parameters.AddWithValue("@tamanho", this.cmb_tamanho.Text);
                cmd.Parameters.AddWithValue("@preco", this.txt_preco.Text);

                MySqlDataReader rs = cmd.ExecuteReader();
                rs.Read();

                if (!rs.HasRows)
                {
                    conn.Close();
                    new SuccessDialog("Pizza cadastrada com sucesso!");
                    this.Close();
                }
                else
                {
                    String error = rs.GetString(0);
                    conn.Close();
                    new ErrorDialog(error);
                }
            }
            catch (Exception err)
            {
                if (conn != null) conn.Close();
                new ErrorDialog(err.Message);
            }
        }
예제 #30
0
파일: ContaDAO.cs 프로젝트: Swadish/pay2me
        public String consultaSaldo(string email)
        {
            try
            {
                string saldo = "";
                DB db = new DB();

                db.OpenConnection();

                String sql = "SELECT c.saldo, c.email, s.`desc` FROM contas c inner join situacao_conta s on c.idsituacao = s.idsituacao where email=@email;";

                MySqlCommand cmd = new MySqlCommand(sql, db.con);
                cmd.Prepare();
                cmd.Parameters.AddWithValue("@email", email);

                db.result = cmd.ExecuteReader();
                if (db.result.Read())
                {
                    saldo = db.result.GetString(0);
                }
                db.CloseConnection();

                return saldo;
            }
            catch
            {
                return "erro";
            }
        }
예제 #31
0
        public void create()
        {
            db = new Database();

            if (officeVerification())
            {
                try
                {
                    officeQuery = new MySqlCommand();

                    officeQuery.Connection = db.Connection();

                    officeQuery.CommandText = "INSERT INTO office(officedescription) VALUES(@Description)";

                    officeQuery.Prepare();

                    officeQuery.Parameters.AddWithValue("@Description", officedescription);

                    officeQuery.ExecuteNonQuery();

                    MessageBox.Show("A Descrição Cargo Assinatura " + officedescription + " foi criada com sucesso.");
                }
                catch (MySqlException ex)
                {
                    MessageBox.Show("Ocurreu um erro");
                    Console.WriteLine("Error: {0}", ex.ToString());
                }
                finally
                {
                    db.Close();
                }
            }
        }
예제 #32
0
        public void GravarRetornoViagem(Viagem v)
        {
            try
            {
                MySqlConnection conn = new ConexaoBancoMySQL().getConnection();
                conn = new MySqlConnection(connectionString);
                String alteratDados = "UPDATE viagem set dta_retorno = @dtaRetornoViagem, km_cidade_retorno = @kmRetorno where id_viagem = @id";
                conn.Open();
                MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(alteratDados, conn);
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("dtaRetornoViagem", v.DtaRetorno));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("id", v.Id_viagem));
                cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("kmRetorno", v.KmRetorno));



                cmd.Prepare();
                cmd.ExecuteNonQuery();

                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro ao cadastrar o usuario, verifique a conexão com o banco de dados: " + ex.ToString());
            }
        }
예제 #33
0
파일: Album.cs 프로젝트: altaria/Altaria
        public int retrieveAlbumId()
        {
            DBConnect connection = new DBConnect();

            string query = "SELECT albumId FROM Album WHERE albumName LIKE @albumName;";

            try
            {
                MySqlCommand cmd = new MySqlCommand(query, connection.OpenConnection());
                cmd.CommandText = query;
                cmd.Prepare();
                cmd.Parameters.AddWithValue("@albumName", this.albumName);

                albumId = int.Parse(cmd.ExecuteScalar() + "");

                cmd.ExecuteNonQuery();

                connection.CloseConnection();

                return albumId;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }
        public void DeleteInschrijving(int studentID, int evenementID)
        {
            MySqlTransaction trans = null;
            try
            {
                conn.Open();
                trans = conn.BeginTransaction();
                string insertString = @"delete from inschrijving where student_id=@studentid and evenement_id=@evenementid";

                MySqlCommand cmd = new MySqlCommand(insertString, conn);
                MySqlParameter studentidParam = new MySqlParameter("@studentid", MySqlDbType.Int32);
                MySqlParameter evenementidParam = new MySqlParameter("@evenementid", MySqlDbType.Int32);

                studentidParam.Value = studentID;
                evenementidParam.Value = evenementID;

                cmd.Parameters.Add(studentidParam);
                cmd.Parameters.Add(evenementidParam);
                cmd.Prepare();
                cmd.ExecuteNonQuery();

                trans.Commit();

            }
            catch (Exception e)
            {
                trans.Rollback();
                Console.Write("Inschrijving niet verwijderd: " + e);
                throw e;
            }
            finally
            {
                conn.Close();
            }
        }
        public static bool addResignationRecord()
        {
            DBConnector dbcon = new DBConnector();

            //try
            //{
            if (dbcon.openConnection())
            {
                MySqlCommand cmd = new MySqlCommand();
                cmd.CommandText = "INSERT INTO resignation (letter_submitted_date, resignation_date, employee_idemployee) VALUES ('" + DateTime.Now.ToString("yyyy-MM-dd") + "', '" + DateTime.Now.ToString("yyyy-MM-dd") + "', " + Employee.employee_id + ")";
                cmd.Connection = dbcon.connection;
                cmd.Prepare();
                cmd.ExecuteNonQuery();

                dbcon.closeConnection();
                return true;
            }
            else
            {
                dbcon.closeConnection();
                return false;
            }

            /*}
            catch (MySqlException e)
            {
                int errorcode = e.Number;
                dbcon.closeConnection();
                return false;
            }*/
        }
        public void BinaryAndVarBinaryParameters()
        {
            if (Version < new Version(5, 0)) return;

              execSQL("CREATE PROCEDURE spTest(OUT out1 BINARY(20), OUT out2 VARBINARY(20)) " +
              "BEGIN SET out1 = 'out1'; SET out2='out2'; END");

              MySqlCommand cmd = new MySqlCommand("spTest", conn);
              cmd.CommandType = CommandType.StoredProcedure;
              cmd.Parameters.Add("out1", MySqlDbType.Binary);
              cmd.Parameters[0].Direction = ParameterDirection.Output;
              cmd.Parameters.Add("out2", MySqlDbType.VarBinary);
              cmd.Parameters[1].Direction = ParameterDirection.Output;
              if (prepare) cmd.Prepare();
              cmd.ExecuteNonQuery();

              byte[] out1 = (byte[])cmd.Parameters[0].Value;
              Assert.AreEqual('o', out1[0]);
              Assert.AreEqual('u', out1[1]);
              Assert.AreEqual('t', out1[2]);
              Assert.AreEqual('1', out1[3]);

              out1 = (byte[])cmd.Parameters[1].Value;
              Assert.AreEqual('o', out1[0]);
              Assert.AreEqual('u', out1[1]);
              Assert.AreEqual('t', out1[2]);
              Assert.AreEqual('2', out1[3]);
        }
예제 #37
0
        public async Task <bool> CheckTestForStudent()
        {
            bool check = false;
            int  test  = 0;

            try
            {
                new I18N.West.CP1250();
                string Connect = "Database=u0354899_diplom;Data Source=31.31.196.162;User Id=u0354899_vlad;Password=vlad19957;charset=utf8";
                MySql.Data.MySqlClient.MySqlConnection myConnection = new MySql.Data.MySqlClient.MySqlConnection(Connect);
                MySql.Data.MySqlClient.MySqlCommand    myCommand    = new MySql.Data.MySqlClient.MySqlCommand();
                myConnection.Open();
                myCommand.Connection  = myConnection;
                myCommand.CommandText = string.Format("SELECT count(*) From test_history WHERE idstudent = '{0}' AND idtest = '{1}'", Student.idStudent, Student.idTest); //запрос: если есть такой логин в таблице
                myCommand.Prepare();                                                                                                                                      //подготавливает строку
                myCommand.ExecuteNonQuery();                                                                                                                              //выполняет запрос
                test = Convert.ToInt32(myCommand.ExecuteScalar());                                                                                                        //результат запроса
                if (test == 0)
                {
                    check = true;
                }
                else
                {
                    check = false;
                }
                myConnection.Close();
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
            }
            return(await Task <bool> .FromResult(check));
        }
예제 #38
0
 public UserModel(int id)
 {
     try {
         MySqlConnection Conn = new MySqlConnection("server=sql9.freemysqlhosting.net;database=sql9140372;user=sql9140372;password=WSx2C8iRZx;");
         var             cmd  = new MySql.Data.MySqlClient.MySqlCommand();
         Conn.Open();
         cmd.Connection  = Conn;
         cmd.CommandText = "SELECT username,currency,avatar,email FROM users WHERE id = @id";
         cmd.Prepare();
         cmd.Parameters.AddWithValue("@id", id);
         MySqlDataReader rdr = cmd.ExecuteReader();
         if (rdr.Read())
         {
             username = rdr[0].ToString();
             currency = Convert.ToInt32(rdr[1]);
             avatar   = rdr[2].ToString();
             if (avatar.Length == 0)
             {
                 avatar = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ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IJydtuXJHsSRXQab+ybYzlP7V/tC75yV3iNT/3yAf1r6+Txh8KkOV8UaJ/4FJ/jVhPHvwxj+54q0Qf9vKf40AeJ+B/gRp3hbb/AGH4ftrFsbWkjiG9h7v94/ia9X0LwVdWu0uMAVtL8R/hyn3fF+jD6XSf40//AIWZ8Pf+hy0j/wAC0/xoA2rCx+yIAWyQKxfib/yT3xF/2DZ//QDR/wALM+Hv/Q5aR/4Fp/jXP+P/AB/4I1HwRrtjY+K9LnnnsJo4oo7lGd3KHAAzzQB//9k=";
             }
             email = rdr[3].ToString();
         }
         else
         {
             username = "******";
             currency = 0;
             avatar   = "";
         }
         Conn.Close();
     } catch (Exception e)
     {
     }
 }
        public static bool addQualification(Qualification q)
        {
            DBConnector dbcon = new DBConnector();

            try
            {
                if (dbcon.openConnection())
                {
                    MySqlCommand cmd = new MySqlCommand();
                    cmd.CommandText = "INSERT INTO qualification (qualification_no, institute, months, occupation_relevant, highest_qualification, status, note, qualification, year, employee_idemployee) VALUES (N'" + q.qualification_no + "', N'" + q.institute + "', N'" + q.months + "', " + q.occupation_relevant + ", " + q.highest_qualification + ", N'" + q.status + "', N'" + q.note + "', N'" + q.qualification + "', N'" + q.year + "', " + Employee.employee_id + ")";
                    cmd.Connection = dbcon.connection;
                    cmd.Prepare();
                    cmd.ExecuteNonQuery();

                    dbcon.closeConnection();
                    return true;
                }
                else
                {
                    dbcon.closeConnection();
                    return false;
                }

            }
            catch (MySqlException e)
            {
                int errorcode = e.Number;
                dbcon.closeConnection();
                return false;
            }
        }
        public static DepartmentModel Load(int id)
        {
            using (var connection = new MySqlConnection(Settings.Default.ConnectionString))
            {
                connection.Open();
                var query = "SELECT Id, Name FROM Department WHERE Id = @id";
                MySqlCommand cmd = new MySqlCommand(query, connection);
                cmd.Parameters.Add(new MySqlParameter("@id", MySqlDbType.Int32));
                cmd.Prepare();

                cmd.Parameters["@id"].Value = id;
                MySqlDataReader reader = cmd.ExecuteReader();
                if (reader.Read() && !reader.IsDBNull(0))
                {
                    var department = new DepartmentModel
                    {
                        Id = reader.GetInt32("Id"),
                        Name = reader.GetString("Name")
                    };
                    return department;
                }
                else
                {
                    //throw new NotSupportedArgument("Id not found");
                    return null;
                }
            }
        }
예제 #41
0
        public void create()
        {
            db = new Database();

            if (vendorVerification())
            {
                try
                {
                    vendorQuery = new MySqlCommand();

                    vendorQuery.Connection = db.Connection();

                    vendorQuery.CommandText = "INSERT INTO vendor(vendorname) VALUES(@Name)";
                    vendorQuery.Prepare();

                    vendorQuery.Parameters.AddWithValue("@Name", vendorname);

                    vendorQuery.ExecuteNonQuery();

                    MessageBox.Show("O fornecedor " + vendorname + " foi criado com sucesso.");
                }
                catch (MySqlException ex)
                {
                    MessageBox.Show("Ocurreu um erro");
                    Console.WriteLine("Error: {0}", ex.ToString());
                }
                finally
                {
                    db.Close();
                }
            }
        }
        private void btnEnvoyer_Click(object sender, EventArgs e)
        {
            MySqlCommand cmd;

            //Global.Connection.Open();
            try
            {
                if (comboBox1.Text == "Sélectionnez la nature de votre requête")
                {
                    MessageBox.Show("Veuillez renseigner la nature de votre requête", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }else if(rtbContenu.Text == "")
                {
                    MessageBox.Show("Veuillez écrire votre requête", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
                } else {
                    cmd = new MySqlCommand("INSERT INTO requetecontact(idUtilisateur, contenu, dateContact, dateTraitement) VALUES(@idUtilisateur, @contenu, now(), '1000-01-01 00:00:00')", Global.Connection);
                    MySqlParameter pIdUtilisateur = new MySqlParameter("@idUtilisateur", MySqlDbType.Int16);
                    MySqlParameter pContenu = new MySqlParameter("@contenu", MySqlDbType.Text);
                    pIdUtilisateur.Value = Global.userId;
                    pContenu.Value = comboBox1.Text + " : " + rtbContenu.Text;
                    cmd.Parameters.Add(pIdUtilisateur);
                    cmd.Parameters.Add(pContenu);
                    cmd.Prepare();
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("Votre reqûete a bien été prise en compte, nos équipes sont au travail ! ", "Succès", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    rtbContenu.Text = "";
                    comboBox1.SelectedItem = "Sélectionnez la nature de votre requête";
                }
            } catch (MySqlException) {
                MessageBox.Show("Une erreur est survenue. Impossible de contiuer.", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
                rd.Close();
                Global.Connection.Close();
            }
        }
예제 #43
0
        /// <summary>
        /// Ajoute une salle à base de donneés.
        /// </summary>
        /// <param name="connectionString">Les paramètres de connexion à la base de données.</param>
        /// <param name="salleDTO">Représente la salle qui sera ajouté.</param>
        public void Add(string connectionString, SalleDTO salleDTO)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new DAOException("Les paramètres de connexion n'ont pas été initialisé.");
            }

            try
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    connection.Open();
                    MySqlCommand addPreparedStatement = new MySqlCommand(SalleDAO.ADD_REQUEST, connection);
                    addPreparedStatement.Parameters.AddWithValue("@numero", salleDTO.Numero);
                    addPreparedStatement.Parameters.AddWithValue("@etage", salleDTO.Etage);
                    addPreparedStatement.Parameters.AddWithValue("@bloc", salleDTO.Bloc);
                    addPreparedStatement.Prepare();
                    addPreparedStatement.ExecuteNonQuery();
                }
            }
            catch (SqlException sqlException)
            {
                throw new DAOException(sqlException.Message, sqlException);
            }
        }
예제 #44
0
        public void create()
        {
            db = new Database();

            space = new Space();

            try
            {
                pathQuery = new MySqlCommand();

                pathQuery.Connection = db.Connection();

                pathQuery.CommandText = "INSERT INTO path(path) VALUES(@Path)";

                pathQuery.Prepare();

                pathQuery.Parameters.AddWithValue("@Path", path);

                pathQuery.ExecuteNonQuery();

                MessageBox.Show("O Caminho " + path + " foi criado com sucesso.");
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("Ocurreu um erro");

                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                db.Close();
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            int count = context.Request.GetQueryStringInteger("queries", 1).Clamp(1, 500);
            World[] worlds = new World[count];
            Random random = new Random();

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

                using (MySqlCommand command = new MySqlCommand(DB_QUERY, connection))
                {
                    command.Prepare();
                    command.Parameters.Add("@id", MySqlDbType.Int32);

                    for (int i = 0; i < count; i++)
                    {
                        int id = random.Next(1, DB_ROWS);
                        command.Parameters["@id"].Value = id;

                        using (MySqlDataReader reader = command.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                worlds[i] = new World(id, reader.GetInt32("randomNumber"));
                            }
                        }
                    }
                }
            }

            JsonHelpers.WriteJson(worlds, context);
        }
        public void create()
        {
            db = new Database();

            if (categoryVerification())
            {
                try
                {
                    actiontypeQuery = new MySqlCommand();

                    actiontypeQuery.Connection = db.Connection();

                    actiontypeQuery.CommandText = "INSERT INTO actiontype(actiontypedescription) VALUES(@Description)";
                    actiontypeQuery.Prepare();

                    actiontypeQuery.Parameters.AddWithValue("@Description", actiontypedescription);

                    actiontypeQuery.ExecuteNonQuery();

                    MessageBox.Show("O tipo de ação " + actiontypedescription + " foi criado com sucesso.");
                }
                catch (MySqlException ex)
                {
                    MessageBox.Show("Ocurreu um erro");
                    Console.WriteLine("Error: {0}", ex.ToString());
                }
                finally
                {
                    db.Close();
                }
            }
        }
예제 #47
0
 public bool AutenticarUsuario(Usuario u)
 {
     try
     {
         MySqlConnection conn = new ConexaoBancoMySQL().getConnection();
         conn = new MySqlConnection(connectionString);
         String validarUsuario = "SELECT * FROM cadastro_usuario WHERE nome_usuario = @nome AND senha_usuario = MD5(@senha) AND ativo = 's';";
         conn.Open();
         MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(validarUsuario, conn);
         cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("nome", u.Nome));
         cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("senha", u.Senha));
         cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("ativo", u.Ativo));
         int retorno = Convert.ToInt32(cmd.ExecuteScalar());
         cmd.Prepare();
         cmd.ExecuteNonQuery();
         conn.Close();
         if (retorno > 0)
         {
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Dados incorretos, informe novamente! " + ex.ToString());
         return(false);
     }
 }
예제 #48
0
        public void DeleteGenre(int genreId)
        {
            MySqlTransaction trans = null;
            try
            {
                conn.Open();
                trans = conn.BeginTransaction();
                string insertString = @"delete from genre where genre_id=@id";

                MySqlCommand cmd = new MySqlCommand(insertString, conn);
                MySqlParameter idParam = new MySqlParameter("@id", MySqlDbType.Int32);
                idParam.Value = genreId;

                cmd.Parameters.Add(idParam);
                cmd.Prepare();
                cmd.ExecuteNonQuery();

                trans.Commit();

            }
            catch (Exception e)
            {
                trans.Rollback();
                Console.Write("Genre niet verwijderd: " + e);
                throw e;
            }
            finally
            {
                conn.Close();
            }
        }
        public int GetFactuurId()
        {
            int id = 0;

            try
            {
                conn.Open();
                string getQuery = @"select max(factuur_code) as factuur_code from factuur";

                MySqlCommand cmd = new MySqlCommand(getQuery, conn);

                cmd.Prepare();

                MySqlDataReader dataReader = cmd.ExecuteReader();
                if (dataReader.Read())
                {
                    id = GetFactuurIdFromDataReader(dataReader);
                }
            }
            catch (Exception e)
            {
                // Moet naar error page, niet alleen throw e
                throw e;
            }
            finally
            {
                conn.Close();
            }
            return id;
        }
예제 #50
0
        public bool DeleteMemberType(int memberTypeId)
        {
            MySqlConnection cnn = DBUtility.getConnection();
            if (cnn != null)
            {
                try
                {
                    cnn.Open();
                    const string SQL = @"DELETE FROM 
											membertypes 
										WHERE 
											membertypeid = @membertypeid";
                    MySqlCommand command = new MySqlCommand(SQL, cnn);
                    command.Prepare();
                    command.Parameters.AddWithValue("@membertypeid", memberTypeId);
                    if (command.ExecuteNonQuery() > 0)
                    {
                        return true;
                    }
                }
                catch (MySqlException e)
                {
                    Console.WriteLine(e);
                }
                finally
                {
                    cnn.Close();
                }
            }
            return false;
        }
예제 #51
0
 /// <summary>
 /// Ajoute un entraineur à la base de données.
 /// </summary>
 /// <param name="connectionString">Les paramètres de connexion à la base de données.</param>
 /// <param name="entraineurDTO">Représente l'entraineur qui sera ajouté.</param>
 public void Add(string connectionString, EntraineurDTO entraineurDTO)
 {
     if (string.IsNullOrEmpty(connectionString))
     {
         throw new DAOException("Les paramètres de connexion n'ont pas été initialisé.");
     }
     try
     {
         using (MySqlConnection connection = new MySqlConnection(connectionString))
         {
             connection.Open();
             MySqlCommand addPreparedStatement = new MySqlCommand(EntraineurDAO.ADD_REQUEST, connection);
             addPreparedStatement.Parameters.AddWithValue("@nom", entraineurDTO.Nom);
             addPreparedStatement.Parameters.AddWithValue("@prenom", entraineurDTO.Prenom);
             addPreparedStatement.Parameters.AddWithValue("@adresse", entraineurDTO.Adresse);
             addPreparedStatement.Parameters.AddWithValue("@ville", entraineurDTO.Ville);
             addPreparedStatement.Parameters.AddWithValue("@telephone", entraineurDTO.Telephone);
             addPreparedStatement.Parameters.AddWithValue("@email", entraineurDTO.Email);
             addPreparedStatement.Parameters.AddWithValue("@sexe", entraineurDTO.Sexe);
             addPreparedStatement.Parameters.AddWithValue("@dateNaissance", entraineurDTO.DateNaissance);
             addPreparedStatement.Prepare();
             addPreparedStatement.ExecuteNonQuery();
         }
     }
     catch (SqlException sqlException)
     {
         throw new DAOException(sqlException.Message, sqlException);
     }
 }
예제 #52
0
        /// <summary>
        /// Ajoute une activité.
        /// </summary>
        /// <param name="connectionString">Les paramètres de connexion à la base de données.</param>
        /// <param name="activiteDTO">Représente l'activité qui sera ajouté.</param>
        public void Add(string connectionString, ActiviteDTO activiteDTO)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new DAOException("Les paramètres de connexion n'ont pas été initialisé.");
            }

            try
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    connection.Open();
                    MySqlCommand addPreparedStatement = new MySqlCommand(ActiviteDAO.ADD_REQUEST, connection);
                    addPreparedStatement.Parameters.AddWithValue("@nom", activiteDTO.Nom);
                    addPreparedStatement.Parameters.AddWithValue("@cout", activiteDTO.Cout);
                    addPreparedStatement.Parameters.AddWithValue("@duree", activiteDTO.Duree);
                    addPreparedStatement.Parameters.AddWithValue("@description", activiteDTO.Description);
                    addPreparedStatement.Prepare();
                    addPreparedStatement.ExecuteNonQuery();
                }
            }
            catch (SqlException sqlException)
            {
                throw new DAOException(sqlException.Message, sqlException);
            }
        }
예제 #53
0
        public static bool updateStatus(int status,int idShop)
        {
            using (MySqlConnection conn = new MySqlConnection(DiscountStringConnecting))
            {
                try
                {
                    conn.Open();

                    MySqlCommand cmd = new MySqlCommand("UPDATE mag_status SET `status` = @val1 WHERE id = @val2  ", conn);
                    cmd.CommandTimeout = Connector.commandTimeout;
                    cmd.Parameters.AddWithValue("@val1", status);
                    cmd.Parameters.AddWithValue("@val2", idShop);
                    cmd.Prepare();

                    int i = cmd.ExecuteNonQuery();

                    if (i == 1)
                    {
                        Color.WriteLineColor("Shop [" + idShop + "] обновлен статус - " + Common.returnStatusText(status), ConsoleColor.Yellow);
                        return true;
                    }
                    else
                    {
                        Color.WriteLineColor("Shop [" + idShop + "]  Не удалось обновить статус.", ConsoleColor.Red);
                        return false;
                    }
                }
                catch (Exception exc)
                {
                    Color.WriteLineColor("[updateStatus]" + exc.Message, ConsoleColor.Red);
                    Log.Write(exc.Message, "[updateStatus]");
                    return false;
                }
            }
        }
예제 #54
0
 public PasswordModel(int id, string oldPassword, string newPassword, string Confirm)
 {
     passwordError = newpasswordError = confirmError = "";
     success       = true;
     if (oldPassword.Length == 0)
     {
         success       = false;
         passwordError = "Please enter your old password";
     }
     if (newPassword.Length == 0)
     {
         success          = false;
         newpasswordError = "Enter a new password!!";
     }
     if (Confirm.Length == 0)
     {
         success      = false;
         confirmError = "CONFIRM YOUR PASSWORD!";
     }
     if (success == true && !newPassword.Equals(Confirm))
     {
         success      = false;
         confirmError = "Your passwords do not match.";
     }
     if (success == true)
     {
         try
         {
             MySqlConnection Conn = new MySqlConnection("server=sql9.freemysqlhosting.net;database=sql9140372;user=sql9140372;password=WSx2C8iRZx;");
             var             cmd  = new MySql.Data.MySqlClient.MySqlCommand();
             Conn.Open();
             cmd.Connection  = Conn;
             cmd.CommandText = "SELECT password FROM users WHERE id=" + id;
             //cmd.Prepare();
             //cmd.Parameters.AddWithValue("@src", src);
             MySqlDataReader rdr = cmd.ExecuteReader();
             if (rdr.Read() && Crypto.VerifyHashedPassword(rdr[0].ToString(), oldPassword))
             {
                 cmd = new MySql.Data.MySqlClient.MySqlCommand();
                 Conn.Close();
                 Conn.Open();
                 cmd.Connection  = Conn;
                 cmd.CommandText = "UPDATE users SET password=@myawesomepassword WHERE id=" + id;
                 cmd.Prepare();
                 cmd.Parameters.AddWithValue("@myawesomepassword", Crypto.HashPassword(newPassword));
                 cmd.ExecuteNonQuery();
                 Conn.Close();
             }
             else
             {
                 passwordError = "Your old password is incorrect";
             }
         }
         catch (Exception e)
         {
             confirmError = e.Message;
         }
     }
 }
예제 #55
0
 public PaymentModel(int id, string amount, string name, string cardNumber, string cvc, string expires, string password)
 {
     success     = true;
     amountError = nameError = cardNumberError = cvcError = expiresError = passwordError = "";
     if (amount.Length == 0)
     {
         success     = false;
         amountError = "Enter an Amount";
     }
     if (name.Length == 0)
     {
         success   = false;
         nameError = "Enter the Name on the Card";
     }
     if (cardNumber.Length == 0)
     {
         success         = false;
         cardNumberError = "Enter Card Number";
     }
     if (cvc.Length == 0)
     {
         success  = false;
         cvcError = "Enter the Card's CVC";
     }
     if (expires.Length == 0)
     {
         success      = false;
         expiresError = "Enter the Card's expiration date";
     }
     if (expires.Length == 0)
     {
         success       = false;
         passwordError = "Enter your password";
     }
     if (success)
     {
         try
         {
             MySqlConnection Conn = new MySqlConnection("server=sql9.freemysqlhosting.net;database=sql9140372;user=sql9140372;password=WSx2C8iRZx;");
             var             cmd  = new MySql.Data.MySqlClient.MySqlCommand();
             Conn.Open();
             cmd.Connection  = Conn;
             cmd.CommandText = "INSERT INTO payment_info (user_id, name, card_number, cvc) VALUES (@id, @name, @card_number, @cvc)";
             cmd.Prepare();
             cmd.Parameters.AddWithValue("@id", id);
             cmd.Parameters.AddWithValue("@name", name);
             cmd.Parameters.AddWithValue("@card_number", cardNumber);
             cmd.Parameters.AddWithValue("@cvc", cvc);
             success     = cmd.ExecuteNonQuery() > 0;
             amountError = cmd.LastInsertedId.ToString();
             Conn.Close();
         }
         catch (Exception ex)
         {
             amountError = ex.Message;
         }
     }
 }
예제 #56
0
        private void button6_Click(object sender, EventArgs e)
        {
            try
            {
                string Connect = "Database=vlad_m;Data Source=192.168.27.79;User Id=vlad_m;charset=cp1251;default command timeout = 240;Password=vlad19957";
                MySql.Data.MySqlClient.MySqlConnection myConnection = new MySql.Data.MySqlClient.MySqlConnection(Connect);
                MySql.Data.MySqlClient.MySqlCommand    myCommand    = new MySql.Data.MySqlClient.MySqlCommand();
                myConnection.Open();
                myCommand.Connection = myConnection;

                myCommand.CommandText = string.Format("TRUNCATE TABLE export_error"); //запрос: если есть такой логин в таблице
                myCommand.Prepare();                                                  //подготавливает строку
                myCommand.ExecuteNonQuery();                                          //выполняет запрос

                myCommand.CommandText = string.Format("insert into export_error " +
                                                      "SELECT * FROM import_error_gis " +
                                                      "WHERE NOT EXISTS(" +
                                                      "SELECT * FROM import_error_LS " +
                                                      "WHERE import_error_LS.id = import_error_gis.id " +
                                                      "and import_error_LS.lastname = import_error_gis.lastname " +
                                                      "and import_error_LS.firtname = import_error_gis.firtname " +
                                                      "and import_error_LS.lastname = import_error_gis.lastname)"); //запрос: если есть такой логин в таблице
                myCommand.Prepare();                                                                                //подготавливает строку
                myCommand.ExecuteNonQuery();                                                                        //выполняет запрос

                myCommand.CommandText = string.Format("select count(id) from export_error");                        //запрос: если есть такой логин в таблице
                myCommand.Prepare();                                                                                //подготавливает строку
                myCommand.ExecuteNonQuery();                                                                        //выполняет запрос
                int count = Convert.ToInt32(myCommand.ExecuteScalar());

                myConnection.Close();
                MessageBox.Show("Готово export_error! Господи, спаси меня это этого: " + count);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #57
0
        public AvatarModel(int id, string src)
        {
            MySqlConnection Conn = new MySqlConnection("server=sql9.freemysqlhosting.net;database=sql9140372;user=sql9140372;password=WSx2C8iRZx;");
            var             cmd  = new MySql.Data.MySqlClient.MySqlCommand();

            Conn.Open();
            cmd.Connection  = Conn;
            cmd.CommandText = "UPDATE users SET avatar=@src WHERE id=" + id;
            cmd.Prepare();
            cmd.Parameters.AddWithValue("@src", src);
            //MySqlDataReader rdr = cmd.ExecuteReader();
            cmd.ExecuteNonQuery();
            Conn.Close();
        }
예제 #58
0
        public void updateState()
        {
            string          output = JsonConvert.SerializeObject(data);
            MySqlConnection Conn   = new MySqlConnection("server=sql9.freemysqlhosting.net;database=sql9140372;user=sql9140372;password=WSx2C8iRZx;");
            var             cmd    = new MySql.Data.MySqlClient.MySqlCommand();

            Conn.Open();
            cmd.Connection  = Conn;
            cmd.CommandText = "INSERT INTO games VALUES output ";
            cmd.Prepare();
            MySqlDataReader rdr = cmd.ExecuteReader();

            Conn.Close();
        }
예제 #59
0
 public EmailModel(int id, string email, string password)
 {
     success       = true;
     passwordError = emailError = "";
     if (email.Length == 0)
     {
         success    = false;
         emailError = "Enter your new email";
     }
     if (password.Length == 0)
     {
         success       = false;
         passwordError = "Enter your password";
     }
     if (success == true)
     {
         try
         {
             MySqlConnection Conn = new MySqlConnection("server=sql9.freemysqlhosting.net;database=sql9140372;user=sql9140372;password=WSx2C8iRZx;");
             var             cmd  = new MySql.Data.MySqlClient.MySqlCommand();
             Conn.Close();
             Conn.Open();
             cmd.Connection  = Conn;
             cmd.CommandText = "SELECT password FROM users WHERE id=" + id;
             //cmd.Prepare();
             //cmd.Parameters.AddWithValue("@src", src);
             MySqlDataReader rdr = cmd.ExecuteReader();
             if (rdr.Read() && Crypto.VerifyHashedPassword(rdr[0].ToString(), password))
             {
                 cmd = new MySql.Data.MySqlClient.MySqlCommand();
                 Conn.Close();
                 Conn.Open();
                 cmd.Connection  = Conn;
                 cmd.CommandText = "UPDATE users SET email=@newemail WHERE id=" + id;
                 cmd.Prepare();
                 cmd.Parameters.AddWithValue("@newemail", email);
                 cmd.ExecuteNonQuery();
                 Conn.Close();
             }
             else
             {
                 passwordError = "Your password is incorrect";
             }
         }
         catch (Exception e)
         {
             passwordError = e.Message;
         }
     }
 }
예제 #60
0
        public string getState()
        {
            MySqlConnection Conn = new MySqlConnection("server=sql9.freemysqlhosting.net;database=sql9140372;user=sql9140372;password=WSx2C8iRZx;");
            var             cmd  = new MySql.Data.MySqlClient.MySqlCommand();

            Conn.Open();
            cmd.Connection  = Conn;
            cmd.CommandText = "SELECT jsondata FROM games";
            cmd.Prepare();
            MySqlDataReader rdr  = cmd.ExecuteReader();
            string          json = (string)rdr["jsondata"];

            //change to point to data class held by this
            data = JsonConvert.DeserializeObject <GameData>(json);

            Conn.Close();
            return(json);
        }