예제 #1
2
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                MySqlConnection myConn = new MySqlConnection();
                myConn.Host = "192.168.69.8";
                myConn.Port = 3306;
                myConn.UserId = "cody";
                myConn.Password = "******";
                myConn.Open();

                MySqlCommand myCommand = new MySqlCommand(" SELECT * FROM registration.regUser ;", myConn);
                MySqlDataAdapter myDataAdapter = new MySqlDataAdapter();
                myDataAdapter.SelectCommand = myCommand;
                DataTable dbDataSet = new DataTable();
                myDataAdapter.Fill(dbDataSet);
                BindingSource bSource = new BindingSource();

                bSource.DataSource = dbDataSet;
                dataGridView1.DataSource = bSource;
                myDataAdapter.Update(dbDataSet);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #2
0
파일: MainWindow.cs 프로젝트: rlloret/AD
	protected void LecturaDeDatos()
	{

		mySqlConnection = new MySqlConnection("DataSource=localhost;" +
		                                      "Database=dbprueba;" +
		                                      "User ID=root;" +
		                                      "Password=sistemas");
		mySqlConnection.Open ();

	    mySqlCommand = mySqlConnection.CreateCommand ();

		mySqlCommand.CommandText = "select * from categoria";

		MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader ();


		//Console.WriteLine ("id.GetType()={0}", IDbCommand.GetType());//Muestra el tipo de dato utilizado

		while (mySqlDataReader.Read()) {

			object id = mySqlDataReader["id"].ToString();
			object nombre = mySqlDataReader["nombre"];
			listStore.AppendValues (id, nombre);

		}
		mySqlDataReader.Close ();

	}
예제 #3
0
    public bool CreatePatient(string fname, string lname, string dob, string sex)
    {
        if ((String.IsNullOrWhiteSpace(fname)) | (String.IsNullOrWhiteSpace(lname)) | (!Patient.IsValidDOB(dob)) | (!Patient.IsValidSex(sex)))
        {
            return false;
        }
        try
        {
            string connString = System.Configuration.ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString;
            MySqlConnection connection = new MySqlConnection(connString);
            MySqlCommand command = connection.CreateCommand();
            command.CommandText = "INSERT INTO patient (first_name, last_name, birth_date, sex) VALUES (@fname, @lname, @dob, @sex)";
            command.Parameters.Add("fname", MySqlDbType.String).Value = fname;
            command.Parameters.Add("lname", MySqlDbType.String).Value = lname;
            command.Parameters.Add("dob", MySqlDbType.Date).Value = String.Format("{0:yyyy-MM-dd}", Convert.ToDateTime(dob));
            command.Parameters.Add("sex", MySqlDbType.Enum).Value = sex;

            connection.Open();
            command.ExecuteReader();
            connection.Close();
            return true;
        }
        catch
        {
            return false;
        }
    }
예제 #4
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!this.IsPostBack)
     {
     /*string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;*/
     string constr = "server=182.50.133.91;database=Techgeekinc_db;" + "uid=techgeek;pwd=techgeek786;";
         using (MySqlConnection con = new MySqlConnection(constr))
         {
             using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM customers"))
             {
                 using (MySqlDataAdapter sda = new MySqlDataAdapter())
                 {
                     cmd.Connection = con;
                     sda.SelectCommand = cmd;
                     using (DataTable dt = new DataTable())
                     {
                         sda.Fill(dt);
                         GridView1.DataSource = dt;
                         GridView1.DataBind();
                     }
                 }
             }
         }
     }
 }
예제 #5
0
파일: DB.cs 프로젝트: nokitty/chaxin
 public DB(string str = "")
 {
     if (str == "")
         str = _conStr;
     _connection = new MySqlConnection(str);
     _connection.Open();
 }
    static void Main(string[] args)
    {
        string connToMySql = @"Server=localhost;Uid=root;Pwd=root;Allow User Variables=True;";

        MySqlConnection connect = new MySqlConnection(connToMySql);

        connect.Open();

        using (connect)
        {
            CreateDB(connect);

            InsertBook(connect, "Steven McTowlie", "A Million Little Fibers", "41124114512125512X", "1995, 04, 12");
            InsertBook(connect, "Steven McTowlie2", "A Million Little Fibers2", "411124114512125512X", "1995, 04, 12");
            InsertBook(connect, "Steven McTowlie3", "A Million Little Fibers3", "4112411451212512X", "1995, 04, 12");
            InsertBook(connect, "Steven McTowlie4", "A Million Little Fibers4", "41124114512532125512X", "1995, 04, 12");

            ListAllBooks(connect);

            Console.Write("Enter a search word:");
            string searchString = Console.ReadLine().Replace("%", "[%]")
                                                .Replace("_", "[_]");
            Console.WriteLine();
            FindBookByName(connect, searchString);
        }
    }
예제 #7
0
		public void StateChange() 
		{
			MySqlConnection c = new MySqlConnection(GetConnectionString(true));
			c.StateChange += new StateChangeEventHandler(StateChangeHandler);
			c.Open();
			c.Close();
		}
    /*
        Lukee yhden käyttäjän kaikki pakat listaan ja palauttaa ne;
    */
    public List<Deck> readAllUserDecksFromDB(int userId)
    {
        List<Deck> tempDecks = new List<Deck>();

        sql = "SELECT * FROM deck WHERE User_idUser="******";";
        MySqlConnection conn = new MySqlConnection(connStr);
        MySqlCommand cmd = new MySqlCommand(sql, conn);
        conn.Open();
        MySqlDataReader reader = cmd.ExecuteReader();
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                tempDecks.Add(new Deck
                {
                    deckId = int.Parse(reader["idDeck"].ToString()),
                    name = reader["DeckName"].ToString(),
                    playerClass = reader["DeckClass"].ToString(),
                    userId = int.Parse(reader["User_idUser"].ToString()),
                    cardCount = int.Parse(reader["CardCount"].ToString()),
                    cards = this.cardsInThisDeck(int.Parse(reader["idDeck"].ToString()))
                });
            }
        }
        reader.Close();
        conn.Close();

        return tempDecks;
    }
예제 #9
0
파일: MainWindow.cs 프로젝트: nerea123/ad
    //ListStore listStore;
    public MainWindow()
        : base(Gtk.WindowType.Toplevel)
    {
        Build ();

        IDbConnection dbConnection= new MySqlConnection("Server=localhost;Database=dbprueba;" +
                "User Id=root;Password=sistemas");
        dbConnection.Open();

        ComboBoxHelper combo= new ComboBoxHelper(dbConnection,Combobox,"nombre","id",1,"categoria");
        //listStore=combo.ListStore;

        //		TreeIter iter;
        //		liststore.GetIterFirst(out iter);
        //		do{
        //			if((int)liststore.GetValue(iter,0)==elementoInicial){
        //				break;
        //			}
        //		}
        //		while(liststore.IterNext(ref iter));

        Combobox.Changed +=delegate{
            Console.WriteLine("El id es {0}",combo.ID);
        };
    }
예제 #10
0
        public void Unicode()
        {
            if (version < new Version(4, 1)) return;

            execSQL("DROP TABLE IF EXISTS Test");
            execSQL("CREATE TABLE Test (u2 varchar(255) CHARACTER SET ucs2)");

            MySqlConnection c = new MySqlConnection(conn.ConnectionString + ";charset=utf8");
            c.Open();

            MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES ( CONVERT('困巫忘否役' using ucs2))", c);
            cmd.ExecuteNonQuery();

            cmd.CommandText = "SELECT * FROM Test";
            MySqlDataReader reader = null;

            try
            {
                reader = cmd.ExecuteReader();
                reader.Read();
                string s1 = reader.GetString(0);
                Assert.AreEqual("困巫忘否役", s1);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
            finally
            {
                if (reader != null) reader.Close();
                c.Close();
            }
        }
예제 #11
0
    private static void AddBook(string bookName, DateTime datePublish, long ISBN, string author)
    {
        MySqlConnection dbConnection = new MySqlConnection(connection);

        dbConnection.Open();
        using (dbConnection)
        {
            string bookStr = "INSERT INTO books " +
          "(titleBook, publishDate, ISBN) VALUES " +
          "(@title, @date, @isbn)";
            MySqlCommand addBook = new MySqlCommand(bookStr, dbConnection);
            addBook.Parameters.AddWithValue("@title", bookName);
            addBook.Parameters.AddWithValue("@date", datePublish);
            addBook.Parameters.AddWithValue("@isbn", ISBN);
            addBook.ExecuteNonQuery();

            MySqlCommand cmdSelectIdentity = new MySqlCommand("SELECT @@Identity", dbConnection);
            ulong insertedRecordId = (ulong)cmdSelectIdentity.ExecuteScalar();

            string authorStr = "INSERT INTO authors " +
                        "(Books_idBooks, AuthorName) VALUES " +
                        "(@bookId, @name)";
            MySqlCommand addAuthor = new MySqlCommand(authorStr, dbConnection);
            addAuthor.Parameters.AddWithValue("@bookId", (int)insertedRecordId);
            addAuthor.Parameters.AddWithValue("@name", author);
            addAuthor.ExecuteNonQuery();
        }
    }
예제 #12
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["username"] == null || (string)Session["usertype"] == "vender")
        {
            Response.Redirect("Login_Page.aspx");
        }
        else
        {
            Button1.Text = Session["username"].ToString();
            String poNum = Request.QueryString["p"];
            pn = poNum;
            String itemid = Request.QueryString["i"];
            ii = itemid;

            Label1.Text = poNum;
            Label2.Text = itemid;

            String uid = Session["uid"].ToString();

            string connStr = "Database=ISI;Data Source=localhost;User Id=root;Password=123999";
            mySqlConn = new MySqlConnection(connStr);
            mySqlConn.Open();

           
            
        }

        
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if ((string)Session["usertype"] == "vender")
        {
            Response.Redirect("Login_Page.aspx");
        }
        if (Session["username"] != null)
        {
            Login.Visible = false;
            Button4.Text = Session["username"].ToString();
        }
        else {
            Button4.Visible = false;
            Logout.Visible = false;
        }
        String itemid = Request.QueryString["id"];
        id = itemid;
        string connStr = "Database=ISI;Data Source=localhost;User Id=root;Password=123999";
        mySqlConn = new MySqlConnection(connStr);
        mySqlConn.Open();

    
        if (!IsPostBack)
        {
            bind(itemid);

        }
    }
예제 #14
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        String aux = "INSERT INTO sala_apartada values(null," + TextBox2.Text + ", " + TextBox3.Text + ", '" + TextBox6.Text + "', '" + TextBox7.Text + "');";
        try
        {
            MySqlConnection Cn;
            MySqlCommand Cm;
            String cadena;
            Cn = new MySqlConnection();
            cadena = "Server=localhost; user=root; database=Laboratorio";
            Cn.ConnectionString = cadena;
            Cn.Open();
            /////Insertar/////
            Cm = new MySqlCommand(aux, Cn);
            Cm.ExecuteNonQuery();
            Cn.Close();
            Label1.Text = "Datos Guardados";
            //Response.Write(@"<script language='javascript'>alert('realizada')</script>");
        }

        catch (MySqlException es)
        {
           // Response.Write(@"<script language='javascript'>alert('Error')</script>");
            Label1.Text = "No se Pudo regsitrar Entrada";
        }
    }
예제 #15
0
    private string USERID = "root"; // ���[�U��

    #endregion Fields

    #region Methods

    void SelectData()
    {
        // SQL�R�}���h��쐬
        string conCmd =
                "server=" + SERVER + ";" +
                "database=" + DATABASE + ";" +
                "userid=" + USERID + ";" +
                "port=" + PORT + ";" +
                "password="******"select * from guidlist", con);
    }
예제 #16
0
파일: Inserir.aspx.cs 프로젝트: portugol/si
    protected void bt_Gravar(object sender, EventArgs e)
    {
        string strConn_Access = ConfigurationManager.ConnectionStrings["ConnectionString_Listar"].ConnectionString;

        MySqlConnection MyConn = new MySqlConnection(strConn_Access);

        string sqlString = "INSERT INTO perguntas " +
                "(Pergunta, Dificuldade, CapituloId, TipoPg) " +
                "VALUES (@Pergunta, @Dificuldade, @CapituloId, @TipoPg);";

        MySqlCommand Cmd = new MySqlCommand(sqlString, MyConn);

        Cmd.Parameters.AddWithValue("@Pergunta", Editor.Content);
        Cmd.Parameters.AddWithValue("@Dificuldade", txt_Dificuldade.Text);
        Cmd.Parameters.AddWithValue("@CapituloId", Drop_Capitulo.Text);
        Cmd.Parameters.AddWithValue("@TipoPg", Drop_Tipo.Text);

        try
        {
            MyConn.Open();

            Cmd.ExecuteNonQuery();

            MyConn.Close();

            lbl_erro.Text = "Dados introduzidos com sucesso!";
            lbl_erro.Visible = true;

        }
        catch (Exception ex)
        {
            lbl_erro.Text = "Houve um erro na introdução dos dados";
            lbl_erro.Visible = true;
        }
    }
예제 #17
0
파일: login.aspx.cs 프로젝트: webertuar/asd
    protected void Button1_Click(object sender, EventArgs e)
    {
        bool dondur = Filtrele.filtrelencek(TextBox1.Text + " " + TextBox2.Text);
        if (dondur)
        {
            MySqlConnection baglanti = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["a"].ConnectionString);
            string str = FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox2.Text, "sha1");
            baglanti.Open();
            MySqlCommand Sorgu = new MySqlCommand("Select * from user where email='" + TextBox1.Text + "' and password='******'", baglanti);

            MySqlDataReader oku = Sorgu.ExecuteReader();
            if (oku.Read())
            {
               
                Session["asd"] =oku["id"];
                Response.Redirect("Default.aspx");
            }
            else
            {
                Response.Write("<script language=javascript>alert('Error! incorrect password  or user  ');</script>");
            }
            baglanti.Close();
        }
        else { Response.Write("<script language=javascript>alert('Çakall!! SQL sorguları kullanma');</script>"); }
    }
예제 #18
0
파일: MainWindow.cs 프로젝트: ruben206/rad
    public void Add()
    {
        //con este metodo recogeremos los datos de los campos y realizaremos una insercion
        // a la base de datos mediante un mysqlcomand y lo ejecutaremos con mysqlNonquery.
        if(!ComprobarCampos()){
            conexion = pc.BuildConnection();
            using (con = new MySqlConnection(conexion)){
                MySqlCommand comando = new MySqlCommand();
                comando.Connection = con;

                comando.CommandType = CommandType.Text;
                comando.CommandText = "INSERT INTO personas (NOMBRE,APELLIDO,EDAD,SEXO,TELEFONO) " +
                    "values (@Nombre,@Apellido,@Edad,@Sexo,@Telefono)";
                comando.Parameters.AddWithValue("@Nombre", entry1.Text);
                comando.Parameters.AddWithValue("@Apellido", entry2.Text);
                comando.Parameters.AddWithValue("@Edad", entry4.Text);
                comando.Parameters.AddWithValue("@Sexo", combobox1.ActiveText);
                comando.Parameters.AddWithValue("@Telefono", entry3.Text);

                try{
                    con.Open();
                    comando.ExecuteNonQuery();
                }catch{
                    con.Dispose();
                    comando.Dispose();
                }
            }
        }
    }
    protected bool sprAdmin(int id)
    {
        string connStr = ConfigurationManager.ConnectionStrings["MySQLConnStr"].ConnectionString;
        MySqlConnection conn = new MySqlConnection(connStr);

        try
        {
            conn.Open();

            string sql = "SELECT typ FROM users WHERE id=@Id;";
            MySqlCommand zapytanie = new MySqlCommand(sql, conn);

            zapytanie.Parameters.Add(new MySqlParameter("@Id", Session["id"].ToString()));

            object wynik = zapytanie.ExecuteScalar();

            if (wynik != null && wynik.ToString() == "A")
            {
                conn.Close();
                return true;
            }

            conn.Close();
        }
        catch (MySqlException ex)
        {
            //Blad.InnerHtml = ex.ToString();
        }

        return false;
    }
예제 #20
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        string sqlQuery;
        string connstr = "server=localhost;user id=admin;password=123456;database=mydb";
        if (this.bid.Value.CompareTo("1") == 0)
        {
            sqlQuery = "update admin set login=0 where rid='" + this.rid.Value + "'";
        }
        else
        {
            sqlQuery = "update reader set login=0 where rid='" + this.rid.Value + "'";
        }

        using (MySqlConnection conn = new MySqlConnection(connstr))
        {
           // string sqlQuery = "update admin,reader set login=1 where rid='" + this.rid.Value + "'";
            MySqlCommand comm = new MySqlCommand(sqlQuery, conn);
            try
            {
                conn.Open();
            }
            catch (Exception ex)
            {
                throw new Exception("数据库连接失败!", ex);
            }
            comm.ExecuteNonQuery();

        }
        Response.Redirect("Default2.aspx");
    }
예제 #21
0
    private static void ListBooks(MySqlConnection dbCon)
    {
        using (dbCon)
        {
            MySqlCommand cmdSelect = new MySqlCommand(
                "SELECT * FROM Books", dbCon);

            Console.WriteLine("Books:");
            Console.WriteLine("ID\tTitle\t\tAuthor\t\tPublish Date\tISBN");
            MySqlDataReader reader = cmdSelect.ExecuteReader();
            using (reader)
            {
                while (reader.Read())
                {
                    int id = (int)reader["BookId"];
                    string title = (string)reader["Title"];
                    string author = (string)reader["Author"];
                    DateTime publishDate = (DateTime)reader["PublishDate"];
                    string isbn = (string)reader["ISBN"];
                    Console.WriteLine("{0}\t{1}\t{2}\t{3:dd.MM.yyyy}\t{4}",
                        id, title.Trim(), author.Trim(), publishDate, isbn.Trim());
                }
            }
        }
    }
예제 #22
0
파일: Inserir.aspx.cs 프로젝트: portugol/si
    protected void bt_Gravar(object sender, EventArgs e)
    {
        string strConn_Access = ConfigurationManager.ConnectionStrings["ConnectionString_Listar"].ConnectionString;

        MySqlConnection MyConn = new MySqlConnection(strConn_Access);

        string sqlString = "INSERT INTO Tipo_Perg " +
                "(Tipo) " +
                "VALUES (@Tipo);";

        MySqlCommand Cmd = new MySqlCommand(sqlString, MyConn);

        Cmd.Parameters.AddWithValue("@Tipo", txt_Tipo.Text);

        try
        {
            MyConn.Open();

            Cmd.ExecuteNonQuery();

            MyConn.Close();

            lbl_erro.Text = "Dados introduzidos com sucesso!";
            lbl_erro.Visible = true;

        }
        catch (Exception ex)
        {
            lbl_erro.Text = "Houve um erro na introdução dos dados";
            lbl_erro.Visible = true;
        }
    }
예제 #23
0
    private static void FindBook(MySqlConnection dbCon)
    {
        Console.WriteLine("Enter Book title");
        string name = Console.ReadLine();
        name = EscapeSQLString(name);
        using (dbCon)
        {
            MySqlCommand cmdSelect = new MySqlCommand(
                "SELECT * FROM Books WHERE Title=@name", dbCon);
            cmdSelect.Parameters.AddWithValue("@name", name);

            Console.WriteLine("Books:");
            Console.WriteLine("ID\tTitle\t\tAuthor\t\tPublish Date\tISBN");
            MySqlDataReader reader = cmdSelect.ExecuteReader();
            using (reader)
            {
                while (reader.Read())
                {
                    int id = (int)reader["BookId"];
                    string title = (string)reader["Title"];
                    string author = (string)reader["Author"];
                    DateTime publishDate = (DateTime)reader["PublishDate"];
                    string isbn = (string)reader["ISBN"];
                    Console.WriteLine("{0}\t{1}\t{2}\t{3:dd.MM.yyyy}\t{4}",
                        id, title.Trim(), author.Trim(), publishDate, isbn.Trim());
                }
            }
        }
    }
예제 #24
0
 private static void InsertBook(MySqlConnection dbCon)
 {
     Console.WriteLine("Enter Book title");
     string title = Console.ReadLine();
     title = EscapeSQLString(title);
     Console.WriteLine("Enter Book author");
     string author = Console.ReadLine();
     author = EscapeSQLString(author);
     Console.WriteLine("Enter Book publish date in format dd.MM.yyyy");
     DateTime publishDate = DateTime.ParseExact(Console.ReadLine(), "dd.MM.yyyy", new CultureInfo("en-US"));
     Console.WriteLine("Enter Book ISBN");
     string isbn = Console.ReadLine();
     isbn = EscapeSQLString(isbn);
     using (dbCon)
     {
         MySqlCommand cmdInsert = new MySqlCommand(
             "INSERT INTO Books(Title, Author, PublishDate, ISBN) " +
             "VALUES (@title, @author, @publishDate, @isbn)", dbCon);
         cmdInsert.Parameters.AddWithValue("@title", title);
         cmdInsert.Parameters.AddWithValue("@author", author);
         cmdInsert.Parameters.AddWithValue("@publishDate", publishDate);
         cmdInsert.Parameters.AddWithValue("@isbn", isbn);
         cmdInsert.ExecuteNonQuery();
     }
 }
    public MySqlDataReader SelectDataFromDatabase(String sql)
    {
        try
        {

            //string connStr = "server=172.16.58.71;port=3306;user=root;database=crawler;password=a;";
            string connStr = "server=208.11.220.249;port=3306;user=suman123456789;database=tgmc11cfb;password=internet;";
            MySqlCommand cmd;
            MySqlDataReader rdr;

            MySqlConnection conn = new MySqlConnection(connStr);
            conn.Open();

            cmd = new MySqlCommand(sql, conn);

            rdr = cmd.ExecuteReader();

            return rdr;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            //em1.Status(ex.ToString());
        }
        return null;
    }
예제 #26
0
    public string insert(string username, string password, string email, string myid, string myidkey, string regip, string regdate, string lastloginip, string lastlogintime, string salt)
    {
        string sql = "";
        try
        {
            MySqlConnection connection1 = new MySqlConnection("Database=allin;Data Source = localhost;User Id = sasa;Password = takeeasy822822");
            mysqldata_conn mysqlcn = new mysqldata_conn();

            MySqlCommand command1 = new MySqlCommand();
            connection1.Open();
            MySqlDataAdapter da1 = new MySqlDataAdapter();
            DataSet ds = new DataSet();
            sql = "insert into uc_members (username,password,email,myid,myidkey,regip,regdate,lastloginip,lastlogintime,salt) values ('" + username + "','" + password + "','" + email + "','" + myid + "','" + myidkey + "','" + regip + "'," + regdate + "," + lastloginip + "," + lastlogintime + ",'" + salt + "')";

            command1 = new MySqlCommand(sql, connection1);
            command1.ExecuteNonQuery();
            command1 = new MySqlCommand("SELECT LAST_INSERT_ID()", connection1);
            da1.SelectCommand = command1;

            da1.Fill(ds, "aa");
            connection1.Close();
            return ds.Tables["aa"].Rows[0][0].ToString();
        }
        catch (Exception ex)
        {
            this.Response.Write(sql);
            return "";
        }
    }
예제 #27
0
    public void ProblemCharsInSQLUTF8()
    {
      if (Version < new Version(4, 1)) return;

      execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), mt MEDIUMTEXT, " +
            "PRIMARY KEY(id)) CHAR SET utf8");

      using (MySqlConnection c = new MySqlConnection(GetConnectionString(true) + ";charset=utf8"))
      {
        c.Open();

        MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?id, ?text, ?mt)", c);
        cmd.Parameters.AddWithValue("?id", 1);
        cmd.Parameters.AddWithValue("?text", "This is my;test ? string–’‘’“”…");
        cmd.Parameters.AddWithValue("?mt", "My MT string: ?");
        cmd.ExecuteNonQuery();

        cmd.CommandText = "SELECT * FROM Test";
        using (MySqlDataReader reader = cmd.ExecuteReader())
        {
          Assert.IsTrue(reader.Read());
          Assert.AreEqual(1, reader.GetInt32(0));
          Assert.AreEqual("This is my;test ? string–’‘’“”…", reader.GetString(1));
          Assert.AreEqual("My MT string: ?", reader.GetString(2));
        }
      }
    }
예제 #28
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        String idSalaT = TextBox4.Text;
        String fecha = "'" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "'";

          // idSalaT=lis

        String consulta = "Insert into mantenimiento values (null, " + fecha + ", " + idSalaT+ ", " + TextBox2.Text.ToString() + ", '" + TextBox3.Text.ToString() + "');";

        // statusMaquina.Text = consulta;

        try
        {
            MySqlConnection Conexion = new MySqlConnection();
            String cadena;
            cadena = "Server=localhost; user=root; database=Laboratorio";
            Conexion.ConnectionString = cadena;
            Conexion.Open();
            MySqlCommand command = new MySqlCommand(consulta, Conexion);
            command.ExecuteNonQuery();
            Conexion.Close();
            Label1.Text = "Datps Guardados";
            //s = true;
        }

        catch (MySqlException ex)
        {
            //Response.Write("<script language='javascript'>alert('Verifica tus Datos')</script>");
            Label1.Text = " Verifica tus Datos";

        }
    }
    public int InsertIntoDatabase(String sql)
    {
        try
        {

            //string connStr = "server=172.16.58.71;port=3306;user=root;database=crawler;password=a;";
            string connStr = "server=208.11.220.249;port=3306;user=suman123456789;database=tgmc11cfb;password=internet;";

            MySqlCommand cmd;

            MySqlConnection conn = new MySqlConnection(connStr);
            conn.Open();

            cmd = new MySqlCommand(sql + ";SELECT LAST_INSERT_ID()", conn);

            int id = Convert.ToInt32(cmd.ExecuteScalar());

            //em1.Status("No Error : Data" + id);
            return (id);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            //em1.Status(ex.ToString());
        }
        return 0;
    }
예제 #30
0
    private static void SearchForBook(string input)
    {
        MySqlConnection dbConnection = new MySqlConnection(connection);

        dbConnection.Open();
        using (dbConnection)
        {

            string sqlStr = "USE `bookStores` ; SELECT AuthorName, titleBook, publishDate, ISBN  FROM books " +
                "JOIN authors " +
                "ON authors.Books_idBooks = books.idBooks " +
                "WHERE titleBook LIKE @input";
            MySqlParameter cmdParam = new MySqlParameter("@input", "%" + input + "%");
            MySqlCommand cmd = new MySqlCommand(sqlStr, dbConnection);
            cmd.Parameters.Add(cmdParam);
            MySqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                string author = (string)reader["AuthorName"];
                string title = (string)reader["titleBook"];
                DateTime date = (DateTime)reader["publishDate"];
                long isbn = (long)reader["ISBN"];
                Console.WriteLine("{0}: {1} {2} {3}", author, title, date, isbn);
            }
        }
    }
예제 #31
0
        /// <summary>
        /// 执行MySql和Oracle滴混合事务
        /// </summary>
        /// <param name="list">SQL命令行列表</param>
        /// <param name="oracleCmdSqlList">Oracle命令行列表</param>
        /// <returns>执行结果 0-由于SQL造成事务失败 -1 由于Oracle造成事务失败 1-整体事务执行成功</returns>
        public static int ExecuteSqlTran(List <CommandInfo> list, List <CommandInfo> oracleCmdSqlList)
        {
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;
                MySqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    foreach (CommandInfo myDE in list)
                    {
                        string           cmdText  = myDE.CommandText;
                        MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters;
                        PrepareCommand(cmd, conn, tx, cmdText, cmdParms);
                        if (myDE.EffentNextType == EffentNextType.SolicitationEvent)
                        {
                            if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
                            {
                                tx.Rollback();
                                throw new Exception("违背要求" + myDE.CommandText + "必须符合select count(..的格式");
                                //return 0;
                            }

                            object obj    = cmd.ExecuteScalar();
                            bool   isHave = false;
                            if (obj == null && obj == DBNull.Value)
                            {
                                isHave = false;
                            }
                            isHave = Convert.ToInt32(obj) > 0;
                            if (isHave)
                            {
                                //引发事件
                                myDE.OnSolicitationEvent();
                            }
                        }
                        if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
                        {
                            if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
                            {
                                tx.Rollback();
                                throw new Exception("SQL:违背要求" + myDE.CommandText + "必须符合select count(..的格式");
                                //return 0;
                            }

                            object obj    = cmd.ExecuteScalar();
                            bool   isHave = false;
                            if (obj == null && obj == DBNull.Value)
                            {
                                isHave = false;
                            }
                            isHave = Convert.ToInt32(obj) > 0;

                            if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
                            {
                                tx.Rollback();
                                throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须大于0");
                                //return 0;
                            }
                            if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
                            {
                                tx.Rollback();
                                throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须等于0");
                                //return 0;
                            }
                            continue;
                        }
                        int val = cmd.ExecuteNonQuery();
                        if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
                        {
                            tx.Rollback();
                            throw new Exception("SQL:违背要求" + myDE.CommandText + "必须有影响行");
                            //return 0;
                        }
                        cmd.Parameters.Clear();
                    }
                    string oraConnectionString = PubConstant.GetConnectionString("ConnectionStringPPC");
                    bool   res = OracleHelper.ExecuteSqlTran(oraConnectionString, oracleCmdSqlList);
                    if (!res)
                    {
                        tx.Rollback();
                        throw new Exception("执行失败");
                        // return -1;
                    }
                    tx.Commit();
                    return(1);
                }
                catch (MySql.Data.MySqlClient.MySqlException e)
                {
                    tx.Rollback();
                    throw e;
                }
                catch (Exception e)
                {
                    tx.Rollback();
                    throw e;
                }
            }
        }
예제 #32
0
 /// <summary>
 /// Returns the default connecition data
 /// </summary>
 private MySqlConnection GetMysqlConnection()
 {
     MySqlConnection mysqlConnection = new MySqlConnection(base.connectionString);
     if (!base.OpenConnection(mysqlConnection, 10)) throw new Exception("Unable to connect");
     return mysqlConnection;
 }
예제 #33
0
 /// <summary>
 /// Returns rows of selected column
 /// </summary>
 /// <typeparam name="T">Return type</typeparam>
 /// <param name="query">Select query</param>
 /// <param name="column">Return column name</param>
 /// <param name="parse">Parses the object of explicit conversion</param>
 /// <param name="parameterData">Parameters</param>
 /// <returns>Selected data</returns>
 public override IEnumerable<T> GetColumn<T>(string query, string column, bool parse, params ParameterData[] parameterData)
 {
     using (MySqlConnection mysqlConnection = GetMysqlConnection())
     using (MySqlCommand mysqlCommand = mysqlConnection.CreateCommand())
         return base.GetColumn<T>(mysqlCommand, query, column, parse, parameterData);
 }
예제 #34
0
 /// <summary>
 /// Returns a idictionary of instances. Instance property name and type must reflect table column name and type
 /// </summary>
 /// <typeparam name="Y">Key type</typeparam>
 /// <typeparam name="T">Instance type</typeparam>
 public override IDictionary<Y, T> GetIDictionary<Y, T>(string keyColumn, string query, bool parseKey, params ParameterData[] parameterData)
 {
     using (MySqlConnection mysqlConnection = GetMysqlConnection())
     using (MySqlCommand mysqlCommand = mysqlConnection.CreateCommand())
         return base.GetIDictionary<Y, T>(mysqlCommand, keyColumn, query, parseKey, parameterData);
 }
예제 #35
0
 /// <summary>
 /// Returns all selected data as a datatable
 /// </summary>
 public override DataTable GetDataTable(string query, params ParameterData[] parameterData)
 {
     using (MySqlConnection mysqlConnection = GetMysqlConnection())
     using (MySqlCommand mysqlCommand = mysqlConnection.CreateCommand())
         return base.GetDataTable(mysqlCommand, query, parameterData);
 }
예제 #36
0
 /// <summary>
 /// Sends query to server
 /// </summary>
 public override int SendQuery(string query, params ParameterData[] parameterData)
 {
     using (MySqlConnection mysqlConnection = GetMysqlConnection())
     using (MySqlCommand mysqlCommand = mysqlConnection.CreateCommand())
         return base.SendQuery(mysqlCommand, query, parameterData);
 }
예제 #37
0
 /// <summary>
 /// Sends generic IEnumerable to specified table and database. Make sure that the Generic properties and data type correspond
 /// to database column name and column type
 /// </summary>
 /// <param name="database">Destination database</param>
 /// <param name="table">Destination table</param>
 /// <param name="listData"></param>
 /// <param name="onDuplicateUpdate"></param>
 public override long BulkSendGeneric<T>(string database, string table, IEnumerable<T> listData, bool onDuplicateUpdate, int updateBatchSize = 1000, bool continueUpdateOnError = false)
 {
     using (MySqlConnection mysqlConnection = GetMysqlConnection())
     using (MySqlCommand mysqlCommand = mysqlConnection.CreateCommand())
         return base.BulkSendGeneric(mysqlCommand, database, table, listData, onDuplicateUpdate, updateBatchSize, continueUpdateOnError);
 }
예제 #38
0
        public static DataTable GetCfLocation(string productCode, DateTime pDate, string lotNo = "")
        {
            try
            {
                using (var conn = new MySqlConnection(Globals.CONN_STR))
                {
                    conn.Open();
                    //and stk.stock_date = (SELECT production_date FROM slaughterhouse.plant WHERE plant_id = 1)
                    string sql = @"
                                Select  p.product_name, stk.lot_no, loc.location_code, loc.location_name,
                                case when p.issue_unit_method = 'W'
                                    then sum(case when stk.transaction_type = '1' then stk.stock_wgh else stk.stock_wgh*-1 end)
                                    else sum(case when stk.transaction_type = '1' then stk.stock_qty else stk.stock_qty*-1 end)
                                    end as qty_wgh, p.issue_unit_method
                                From stock stk, product p, location loc
                                where 1 = 1 
                                 and stk.product_code = @product_code 
                                 and stk.stock_date = @stock_date";
                    if (lotNo != "")
                    {
                        sql += " and stk.lot_no = @lot_no ";
                    }

                    sql += @" and stk.product_code = p.product_code
                                and stk.location_code = loc.location_code
                                group by p.product_name, stk.lot_no,  stk.transaction_type, loc.location_code, loc.location_name, p.issue_unit_method, p.sale_unit_method
                                having case when p.sale_unit_method = 'W'
                                then sum(case when stk.transaction_type = '1' then stk.stock_wgh else stk.stock_wgh*-1 end)
                                else sum(case when stk.transaction_type = '1' then stk.stock_qty else stk.stock_qty*-1 end)
                                end > 0
                                order by stk.lot_no
                                        ";

                    var cmd = new MySqlCommand(sql, conn);
                    cmd.Parameters.AddWithValue("product_code", productCode);
                    cmd.Parameters.AddWithValue("stock_date", pDate.ToString("yyyy-MM-dd"));
                    if (lotNo != "")
                    {
                        cmd.Parameters.AddWithValue("lot_no", lotNo);
                    }
                    var da = new MySqlDataAdapter(cmd);

                    var ds = new DataSet();
                    da.Fill(ds);


                    //var coll = (from p in ds.Tables[0].AsEnumerable()
                    //            select new
                    //            {
                    //                LocationCode = p.Field<int>("location_code"),
                    //                LocationName = p.Field<string>("location_name"),
                    //                LotNo = p.Field<string>("lot_no"),
                    //                QtyWgh = p.Field<decimal>("qty_wgh"),
                    //            }).ToList();
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        return(ds.Tables[0]);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #39
0
 public TasksDbHelper(string db_connection_string)
 {
     db_connection = new MySqlConnection(db_connection_string);
     db_connection.Open();
 }
예제 #40
0
 public AppDb(string connectionString)
 {
     Connection = new MySqlConnection(connectionString);
 }
예제 #41
0
 protected MySqlConnection GetOleDbConnection()
 {
     this.conn = new MySqlConnection(this.ConnectionString);
     return(this.conn);
 }
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            Process process = new Process();

            process.StartInfo.FileName               = "/bin/bash";
            process.StartInfo.Arguments              = "-c 'cat /tmp/tainted.txt'";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();

            using (StreamReader reader = process.StandardOutput) {
                tainted_2 = reader.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }

            tainted_3 = tainted_2;

            if ((Math.Pow(4, 2) <= 42))
            {
                {}
            }
            else if (!(Math.Pow(4, 2) <= 42))
            {
                {}
            }
            else
            {
                StringBuilder text = new StringBuilder(tainted_2);
                text.Replace("&", "&amp;");
                text.Replace("'", "&apos;");
                text.Replace(@"""", "&quot;");
                text.Replace("<", "&lt;");
                text.Replace(">", "&gt;");
                tainted_3 = text.ToString();
            }

            //flaw

            string query = "SELECT * FROM '" + tainted_3 + "'";


            string          connectionString = @"server=localhost;uid=mysql_user;password=mysql_password;database=dbname";
            MySqlConnection dbConnection     = null;

            try {
                dbConnection = new MySqlConnection(connectionString);
                dbConnection.Open();
                MySqlCommand cmd = dbConnection.CreateCommand();
                cmd.CommandText = query;
                MySqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader.ToString());
                }
                dbConnection.Close();
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
예제 #43
0
        private string CheckWriteOnlyGroup(string fileId, string groupId)
        {
            string        isWrite     = "";
            List <string> groupIdList = new List <string>();

            //string groupId = "";
            using (MySqlConnection con = new MySqlConnection("server = 35.240.129.112; user id = asguarduser; database = da_schema"))
            {
                con.Open();

                // Get FIle ID
                //string fileId = "";
                //String fileIdQuery = "SELECT * FROM da_schema.fileInfo WHERE fileName = @nameParam";
                //MySqlCommand getFileIdcmd = new MySqlCommand(fileIdQuery, con);
                //getFileIdcmd.Parameters.AddWithValue("@nameParam", fileName);
                //MySqlDataReader reader = getFileIdcmd.ExecuteReader();
                //if (reader.Read())
                //{
                //    fileId = reader["fileId"].ToString();
                //}
                //reader.Close();
                //MessageBox.Show("FileID : " + fileId);

                // Get Group ID
                //String grpIdQuery = "SELECT * FROM da_schema.groupUsers WHERE userID = @userParam";
                //MySqlCommand getGroupIdcmd = new MySqlCommand(grpIdQuery, con);
                //getGroupIdcmd.Parameters.AddWithValue("@userParam", userId);
                //MySqlDataReader reader2 = getGroupIdcmd.ExecuteReader();
                ////while (reader2.HasRows)
                ////{
                //while (reader2.Read())
                //{
                //    groupIdList.Add(reader2["groupID"].ToString());
                ////    foreach (string i in groupIdList)
                ////{
                ////MessageBox.Show(reader2["groupID"].ToString());
                ////}
                ////MessageBox.Show("GroupID " + reader2["groupId"].ToString());

                //}
                //reader2.Close();
                //for (int i = 0; i < groupIdList.Count; i++)
                //{
                //    MessageBox.Show("Group ID: " + groupIdList[i]);
                //}
                //}
                //    reader2.Close();
                //    MessageBox.Show(groupIdList.ToString());
                //    MessageBox.Show(groupId);
                //    Get Perms

                String       fileWritePermQuery = "SELECT * FROM da_schema.groupFilePermissions WHERE groupID = @groupIdParam AND fileID = @fileIdParam";
                MySqlCommand getFilePermcmd     = new MySqlCommand(fileWritePermQuery, con);
                getFilePermcmd.Parameters.AddWithValue("@fileIdParam", fileId);
                //for (int i = 0; i < groupIdList.Count; i++)
                //{
                getFilePermcmd.Parameters.AddWithValue("@groupIdParam", groupId);
                MySqlDataReader reader3 = getFilePermcmd.ExecuteReader();
                if (reader3.Read())
                {
                    isWrite = reader3["editPermission"].ToString();
                }
                //MessageBox.Show("Is Write = " + isWrite);
                reader3.Close();
                con.Close();
                //MessageBox.Show("Group ID: " + isWrite);
                //}
            }
            return(isWrite);
        }
예제 #44
0
        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
        public static int ExecuteSqlTran(System.Collections.Generic.List <CommandInfo> cmdList)
        {
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                conn.Open();
                using (MySqlTransaction trans = conn.BeginTransaction())
                {
                    MySqlCommand cmd = new MySqlCommand();
                    try
                    {
                        int count = 0;
                        //循环
                        foreach (CommandInfo myDE in cmdList)
                        {
                            string           cmdText  = myDE.CommandText;
                            MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters;
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);

                            if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
                            {
                                if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
                                {
                                    trans.Rollback();
                                    return(0);
                                }

                                object obj    = cmd.ExecuteScalar();
                                bool   isHave = false;
                                if (obj == null && obj == DBNull.Value)
                                {
                                    isHave = false;
                                }
                                isHave = Convert.ToInt32(obj) > 0;

                                if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
                                {
                                    trans.Rollback();
                                    return(0);
                                }
                                if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
                                {
                                    trans.Rollback();
                                    return(0);
                                }
                                continue;
                            }
                            int val = cmd.ExecuteNonQuery();
                            count += val;
                            if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
                            {
                                trans.Rollback();
                                return(0);
                            }
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                        return(count);
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }
예제 #45
0
 public static MySqlConnection Connection()
 {
     MySqlConnection conn = new MySqlConnection(DBConfiguration.ConnectionString);
     return conn;
 }
예제 #46
0
        private void buttonsubmit_Click(object sender, EventArgs e)
        {
            Warn warn = new Warn();

            warn.Warnmessage = "上传中 请稍等";
            warn.Show();
            System.Threading.Thread.Sleep(200);
            try
            {
                if (textBox1.Text.Trim() != String.Empty)
                {
                    String          Strconn = "Server=" + Spy.Main.Severip + ";uid=root;pwd=123456;database=spy;CharSet=utf8"; //链接数据库
                    MySqlConnection conn    = new MySqlConnection(Strconn);
                    conn.Open();                                                                                               //打开数据库
                    MySqlCommand cmd = conn.CreateCommand();
                    cmd.CommandText = "select * from test.feedback order by fid desc limit 1";
                    MySqlDataReader reader = cmd.ExecuteReader();//从数据库中读取数据流存入reader中
                    if (reader.Read())
                    {
                        fid = reader.GetInt32(reader.GetOrdinal("fid")) + 1;
                        reader.Close();
                        //MessageBox.Show(fid.ToString());
                    }
                    else
                    {
                        fid = 1;
                        // MessageBox.Show(fid.ToString());
                    }
                    conn.Close();//获取fid
                    string format;
                    format = Spy.Main.user + DateTime.Now.ToString("yyyy-M-d") + "@" + fid;
                    //MessageBox.Show(format);
                    string exepath = Environment.CurrentDirectory;
                    string str;
                    string upload_p1 = null, upload_p2 = null, upload_p3 = null, upload_p4 = null, upload_txt = null;
                    str = textBox1.Text;
                    if (Directory.Exists(exepath + @"\feedbacktxt\") == false)//如果不存在就创建feedbacktxt文件夹
                    {
                        Directory.CreateDirectory(exepath + @"\feedbacktxt\");
                    }
                    StreamWriter feedbacktxt = new StreamWriter(exepath + @"\feedbacktxt\" + format + ".txt", false); //存在改写 不存在创建
                    feedbacktxt.WriteLine(str);                                                                       //写入
                    feedbacktxt.Close();
                    var upload = new Spy.background.SFTPOperation(Spy.Main.Severip, "22", "root", "Zhang7890078");
                    upload.Put(exepath + @"\feedbacktxt\" + format + ".txt", "/root/txt/" + format + ".txt");
                    upload_txt = format + ".txt";//txt上传

                    if (pic1 != null)
                    {
                        upload.Put(pic1, "/root/feedbackimg/" + format + "@p1.jpg");
                        upload_p1 = format + "@p1.jpg;";
                    }
                    if (pic2 != null)
                    {
                        upload.Put(pic2, "/root/feedbackimg/" + format + "@p2.jpg");
                        upload_p2 = format + "@p2.jpg;";
                    }
                    if (pic3 != null)
                    {
                        upload.Put(pic3, "/root/feedbackimg/" + format + "@p3.jpg");
                        upload_p3 = format + "@p3.jpg;";
                    }
                    if (pic4 != null)
                    {
                        upload.Put(pic4, "/root/feedbackimg/" + format + "@p4.jpg");
                        upload_p4 = format + "@p4.jpg;";
                    }//4张图片上传

                    conn.Open();
                    cmd.CommandText = "insert into test.feedback values(null," + '"' + upload_p1 + upload_p2 + upload_p3 + upload_p4 + '"' + "," + '"' + upload_txt + '"' + "," + Spy.Main.computernum + "," + '"' + Spy.Main.user + '"' + "," + '"' + "未阅读" + '"' + ")";
                    cmd.ExecuteNonQuery();
                    conn.Close();
                    warn.Close();
                    MessageBox.Show("上传成功 可关闭页面");
                }
                else
                {
                    warn.Close();
                    MessageBox.Show("请填写文字内容后,再次上传。");
                }
                //var upload = new Spy.background.SFTPOperation("120.27.47.166", "22", "root", "Zhang7890078");
                //upload.Put(pic1,"/root/img/1.jpg");


                //上传格式 获取fid
                //txt格式 user2016-4-1.fid  图片格式 user2016-4-1.fid.p1
                //定时截图格式 [email protected]
            }
            catch
            {
                warn.Close();
                MessageBox.Show("网络出现问题,提交失败!!请联系管理员。");
            }
        }
예제 #47
0
        public bool Actualizar(BE_EST_CLIENTES e_Cliente)
        {
            bool          booOk      = false;
            int           n_row      = 0;
            DatosMySql    xMiFuncion = new DatosMySql();
            BE_MAE_CLIPRO e_cli      = new BE_MAE_CLIPRO();

            mysConec = xMiFuncion.ReAbrirConeccion(mysConec);

            e_cli.n_idemp     = 0; //e_Cliente.n_idemp;
            e_cli.n_id        = e_Cliente.n_id;
            e_cli.n_idcatemp  = 2;
            e_cli.n_idtipcon  = e_Cliente.n_idtipcon;
            e_cli.n_idtipdoc  = e_Cliente.n_idtipdocide;
            e_cli.c_numdoc    = e_Cliente.c_numdocide;
            e_cli.c_nombre    = e_Cliente.c_nom;
            e_cli.c_nomcli1   = e_Cliente.c_nom1;
            e_cli.c_nomcli2   = e_Cliente.c_nom2;
            e_cli.c_apecli1   = e_Cliente.c_ape1;
            e_cli.c_apecli2   = e_Cliente.c_ape2;
            e_cli.c_dir       = e_Cliente.c_dir;
            e_cli.c_tel       = e_Cliente.c_numtel;
            e_cli.c_fax       = "";
            e_cli.c_nomcon    = e_Cliente.c_nom;
            e_cli.c_email     = "";
            e_cli.c_pagweb    = "";
            e_cli.n_estado    = 1;
            e_cli.n_iddep     = e_Cliente.n_iddep;
            e_cli.n_idpro     = e_Cliente.n_idpro;
            e_cli.n_iddis     = e_Cliente.n_iddis;
            e_cli.n_ageret    = 0;
            e_cli.c_codcen    = "";
            e_cli.n_idven     = 0;
            e_cli.n_idcondpag = 0;
            e_cli.c_letnomgir = "";
            e_cli.c_letgirdir = "";
            e_cli.c_letnumdoc = "";
            e_cli.c_lettel    = "";
            e_cli.n_tipreg    = 1;
            e_cli.d_fchini    = e_Cliente.d_fching;

            booOk = xMiFuncion.StoreEjecutar("mae_clipro_actualizar", e_cli, mysConec, null);

            if (booOk == true)
            {
                booOk = xMiFuncion.StoreEjecutar("est_clientes_actualizar", e_Cliente, mysConec, null);
                if (booOk == true)
                {
                    if (booOk == true)
                    {
                        string[,] arrParametros = new string[1, 3] {
                            { "n_idcli", "System.INT32", e_Cliente.n_id.ToString() }
                        };
                        booOk = xMiFuncion.StoreEjecutar("est_clientesplacas_delete", arrParametros, mysConec);
                        if (booOk == true)
                        {
                            for (n_row = 0; n_row <= l_ClientePlaca.Count - 1; n_row++)
                            {
                                booOk = xMiFuncion.StoreEjecutar("est_clientesplacas_insertar", l_ClientePlaca[n_row], mysConec, null);
                                if (booOk == false)
                                {
                                    b_OcurrioError = xMiFuncion.booOcurrioError;
                                    c_ErrorMensaje = xMiFuncion.StrErrorMensaje;
                                    n_ErrorNumber  = xMiFuncion.IntErrorNumber;
                                    return(booOk);
                                }
                            }
                        }
                    }
                    else
                    {
                        b_OcurrioError = xMiFuncion.booOcurrioError;
                        c_ErrorMensaje = xMiFuncion.StrErrorMensaje;
                        n_ErrorNumber  = xMiFuncion.IntErrorNumber;
                        return(booOk);
                    }
                }
                else
                {
                    b_OcurrioError = xMiFuncion.booOcurrioError;
                    c_ErrorMensaje = xMiFuncion.StrErrorMensaje;
                    n_ErrorNumber  = xMiFuncion.IntErrorNumber;
                    return(booOk);
                }
            }
            else
            {
                b_OcurrioError = xMiFuncion.booOcurrioError;
                c_ErrorMensaje = xMiFuncion.StrErrorMensaje;
                n_ErrorNumber  = xMiFuncion.IntErrorNumber;
                return(booOk);
            }

            return(booOk);
        }
예제 #48
0
        private void button3_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == string.Empty)
            {
                MessageBox.Show("field can't be empty, please enter a value!");
                return;
            }


            if (textBox2.Text == string.Empty)
            {
                MessageBox.Show("field can't be empty, please enter a value!");
                return;
            }

            if (textBox3.Text == string.Empty)
            {
                MessageBox.Show("field can't be empty, please enter a value!");
                return;
            }
            if (textBox4.Text == string.Empty)
            {
                MessageBox.Show("field can't be empty, please enter a value!");
                return;
            }

            if (textBox5.Text == string.Empty)
            {
                MessageBox.Show("field can't be empty, please enter a value!");
                return;
            }
            if (textBox6.Text == string.Empty)
            {
                MessageBox.Show("field can't be empty, please enter a   value!");
                return;
            }

            if (textBox31.Text == string.Empty)
            {
                MessageBox.Show("field can't be empty, please enter a value!");
                return;
            }
            if (textBox32.Text == string.Empty)
            {
                MessageBox.Show("field can't be empty, please enter a value!");
                return;
            }

            if (textBox33.Text == string.Empty)
            {
                MessageBox.Show("field can't be empty, please enter a value!");
                return;
            }
            if (textBox34.Text == string.Empty)
            {
                MessageBox.Show("field can't be empty, please enter a value!");
                return;
            }

            if (textBox35.Text == string.Empty)
            {
                MessageBox.Show("field can't be empty, please enter a value!");
                return;
            }

            MySqlConnection con = new MySqlConnection("server=localhost;user id=root;database=erp_crm");

            con.Open();
            MySqlCommand cmd = new MySqlCommand("INSERT INTO salesreg(`name_prd`, `desc`, `unit_price`, `qty`, `total`,`prd_id`,`name_cus`, `sales_rep`, `grand_total`, `invoice_no`, `month`) VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "', '" + textBox4.Text + "','" + textBox5.Text + "', '" + textBox6.Text + "','" + textBox34.Text + "', '" + textBox33.Text + "','" + textBox31.Text + "', '" + textBox32.Text + "', '" + textBox35.Text + "')", con);

            cmd.ExecuteNonQuery();
            MessageBox.Show("record has been succesfully inserted in the database, Click Ok to proceed in prinitng receipt");
            Form8 myform = new Form8();

            this.Hide();
            myform.Show();
            con.Close();
        }
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            tainted_2 = args[1];

            tainted_3 = tainted_2;

            if ((Math.Pow(4, 2) >= 42))
            {
                {}
            }
            else if (!(Math.Pow(4, 2) >= 42))
            {
                StringBuilder escape = new StringBuilder();
                for (int i = 0; i < tainted_2.Length; ++i)
                {
                    char current = tainted_2[i];
                    switch (current)
                    {
                    case '\\':
                        escape.Append(@"\5c");
                        break;

                    case '*':
                        escape.Append(@"\2a");
                        break;

                    case '(':
                        escape.Append(@"\28");
                        break;

                    case ')':
                        escape.Append(@"\29");
                        break;

                    case '\u0000':
                        escape.Append(@"\00");
                        break;

                    case '/':
                        escape.Append(@"\2f");
                        break;

                    default:
                        escape.Append(current);
                        break;
                    }
                }
                tainted_3 = escape.ToString();
            }

            //flaw

            string query = "SELECT * FROM Articles WHERE id=" + tainted_3;


            string          connectionString = @"server=localhost;uid=mysql_user;password=mysql_password;database=dbname";
            MySqlConnection dbConnection     = null;

            try {
                dbConnection = new MySqlConnection(connectionString);
                dbConnection.Open();
                MySqlCommand cmd = dbConnection.CreateCommand();
                cmd.CommandText = query;
                MySqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader.ToString());
                }
                dbConnection.Close();
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
예제 #50
0
파일: LS.cs 프로젝트: vladu4eg/vodokanal
        public void CreateLS(bool chk_mkd, string path, string name_db)
        {
            if (chk_mkd)
            {
                checkMKD = "and ipadr_new.pomesh <> '' ";
            }
            else
            {
                checkMKD = "";
            }

            MySqlConnection myConnection = new MySqlConnection(Connect);
            MySqlCommand    myCommand    = new MySqlCommand();

            myConnection.Open();
            myCommand.Connection = myConnection;
            if (name_db == "gis_ls")
            {
                myCommand.CommandText = string.Format(@"select distinct mb_ls.ls,   
                mb_ls.ls,
                '',
                'ЛС РСО',
                'Нет',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '', '', '', '', '', '', '',
                mb_ls.ls,
                '',
                tmp_ipadr_new.ipadr,
                case when gis_object_adress.type_dom = 'Многоквартирный'
                    then 'Жилое помещение'
                when gis_object_adress.type_dom = 'Жилой'
                    then ''
                when gis_object_adress.type_dom = 'Жилой дом блокированной застройки'
                    then 'Блок в доме блокированной застройки'
                end JIL,
                case when gis_object_adress.type_dom = 'Многоквартирный'
                    then tmp_ipadr_new.pomesh
                when gis_object_adress.type_dom = 'Жилой'
                    then ''
                when gis_object_adress.type_dom = 'Жилой дом блокированной застройки'
                     then tmp_ipadr_new.pomesh
                end pomesh,
                mb_ls.ls,
                'Договор ресурсоснабжения (ЛС РСО или ЛС РЦ)',
                gis_id.id_gis 
                from mb_ls, tmp_ipadr_new, gis_object_adress, gis_id 
                where mb_ls.ls NOT IN 
                ( 
                SELECT gis_ls.id 
                FROM gis_ls 
                ) 
                and mb_ls.ls = tmp_ipadr_new.id 
                and mb_ls.ls = gis_id.id 
                and tmp_ipadr_new.ipadr = gis_object_adress.HOUSEGUID_fias 
                and gis_object_adress.data_delete = '' 
                -- and tmp_ipadr_new.pomesh = gis_object_adress.kv 
                and gis_id.`status` = 'Размещен' "
                                                      + checkMKD +
                                                      "order by mb_ls.ls; ");
            }
            else
            {
                myCommand.CommandText = string.Format(@"select distinct mb_ls.ls,   
                mb_ls.ls,
                gis_ls_cancel.ls_jky,
                'ЛС РСО',
                'Нет',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '', '', '', '', '', '', '',
                mb_ls.ls,
                '',
                tmp_ipadr_new.ipadr,
                case when gis_object_adress.type_dom = 'Многоквартирный'
                    then 'Жилое помещение'
                when gis_object_adress.type_dom = 'Жилой'
                    then ''
                when gis_object_adress.type_dom = 'Жилой дом блокированной застройки'
                    then 'Блок в доме блокированной застройки'
                end JIL,
                case when gis_object_adress.type_dom = 'Многоквартирный'
                    then tmp_ipadr_new.pomesh
                when gis_object_adress.type_dom = 'Жилой'
                    then ''
                when gis_object_adress.type_dom = 'Жилой дом блокированной застройки'
                     then tmp_ipadr_new.pomesh
                end pomesh,
                mb_ls.ls,
                'Договор ресурсоснабжения (ЛС РСО или ЛС РЦ)',
                gis_id.id_gis 
                from mb_ls, tmp_ipadr_new, gis_object_adress, gis_id, gis_ls_cancel
                where mb_ls.ls = gis_ls_cancel.id
                and mb_ls.ls = tmp_ipadr_new.id 
                and mb_ls.ls = gis_id.id 
                and tmp_ipadr_new.ipadr = gis_object_adress.HOUSEGUID_fias 
                and gis_object_adress.data_delete = '' "
                                                      + checkMKD +
                                                      "order by mb_ls.ls;");
            }
            myCommand.Prepare();//подготавливает строку

            MyDataReader = myCommand.ExecuteReader();

            int y = 1;
            int z = 1;

            while (MyDataReader.Read())
            {
                Ls.AddRow(MyDataReader.GetString(0),
                          MyDataReader.GetString(1),
                          MyDataReader.GetString(2),
                          MyDataReader.GetString(3),
                          MyDataReader.GetString(4),
                          MyDataReader.GetString(5),
                          MyDataReader.GetString(6),
                          MyDataReader.GetString(7),
                          MyDataReader.GetString(8),
                          "", "", "", "", "",

                          /* и правда. Нахуй нужны эти комменты. Лучше потом ванговать.
                           * MyDataReader.GetString(9),
                           * MyDataReader.GetString(10),
                           * MyDataReader.GetString(11),
                           * MyDataReader.GetString(12),
                           * MyDataReader.GetString(13),
                           */
                          MyDataReader.GetString(14),
                          MyDataReader.GetString(15),
                          MyDataReader.GetString(16),
                          MyDataReader.GetString(17),
                          MyDataReader.GetString(18),
                          MyDataReader.GetString(19),
                          MyDataReader.GetString(20));

                adress.AddRow(MyDataReader.GetString(21),
                              MyDataReader.GetString(22),
                              MyDataReader.GetString(23),
                              MyDataReader.GetString(24),
                              MyDataReader.GetString(25));

                dogovor.AddRow(MyDataReader.GetString(26),
                               MyDataReader.GetString(27),
                               MyDataReader.GetString(28));

                z++;

                if (z % 1000 == 0)
                {
                    string path2 = "c:\\gis\\LS" + y + "k.xlsx";

                    Ls.FileSave(path, path2, 1, 2);
                    Ls.Rows.Clear();

                    adress.FileSave(path2, path2, 2, 2);
                    adress.Rows.Clear();

                    dogovor.FileSave(path2, path2, 3, 2);
                    dogovor.Rows.Clear();

                    y++;
                }
            }
            Ls.FileSave(path, "c:\\gis\\LS_Final.xlsx", 1, 2);
            adress.FileSave("c:\\gis\\LS_Final.xlsx", "c:\\gis\\LS_Final.xlsx", 2, 2);
            dogovor.FileSave("c:\\gis\\LS_Final.xlsx", "c:\\gis\\LS_Final.xlsx", 3, 2);


            dogovor.Rows.Clear();
            Ls.Rows.Clear();
            adress.Rows.Clear();

            MyDataReader.Close();
            myConnection.Close();

            MessageBox.Show("Готово! С:\\gis\\");
        }
예제 #51
0
    //NOTE: SaveDataInDb() method will save all the member'fields in DB
    //and also will check an Email Id is already exist or not
    //Will return true if not exist and false if exist

    private void SaveDataInDb(RequiredFieldValidator validatorEmail, Label lblError)
    {
        string selectSqlQuery = "SELECT CustEmailAddr";

        selectSqlQuery += "WHERE CustEmailAddr = @CustEmailAddr";

        string insertSqlQuery = "INSERT INTO customer (";

        insertSqlQuery += "CustId, CustFirstName, CustLastName, CustPwd, CustMobNo, CustEmailAddr) ";
        insertSqlQuery += "VALUES (";
        insertSqlQuery += "@CustId, @CustFirstName, @CustLastName, @CustPwd, @CustMobNo, @CustEmailAddr )";

        MySqlConnection connection = new MySqlConnection(connectionString);

        MySqlCommand cmd = new MySqlCommand(selectSqlQuery, connection);

        MySqlCommand cmdInsert = new MySqlCommand(insertSqlQuery, connection);

        MySqlDataAdapter adapter = new MySqlDataAdapter();

        MySqlDataReader reader;

        // Add the parameters
        cmdInsert.Parameters.AddWithValue("@CustId", MyId);

        cmd.Parameters.AddWithValue("@CustEmailAddr", EmailId);

        cmdInsert.Parameters.AddWithValue("@CustFirstName", CustFirstName);

        cmdInsert.Parameters.AddWithValue("@CustLastName", CustLastName);

        cmdInsert.Parameters.AddWithValue("@CustPwd", GetPwd);

        cmdInsert.Parameters.AddWithValue("@CustMobNo", CustMobNo);

        cmdInsert.Parameters.AddWithValue("@CustEmailAddr", EmailId);

        //Will use Try & catch block to be suscessful connection
        int added = 0;

        try
        {
            //To dispose the connection Obj successfully

            using (connection)
            {
                //Open Databse connection
                connection.Open();
                reader = cmd.ExecuteReader();

                //Will check an Email id is already exist or not

                while (reader.Read())
                {
                    //If exist

                    if (EmailId == reader["CustEmailAddr"].ToString())
                    {
                        validatorEmail.Text  = "Email Id is already exist";
                        validatorEmail.Text += "Click on forgot password";
                    }

                    //If not

                    else
                    {
                        //If inserted successfully it returns 1

                        added = cmdInsert.ExecuteNonQuery();
                    }
                }
            }
        }
        catch (Exception error)
        {
            lblError.Text = error.ToString();
        }

        //If record is added sucessfully set cookie and mail info to client

        if (added > 0)
        {
            //Create cookie
            cookie = new HttpCookie("CustomerInfo");

            // Store CustId to cookie
            cookie["CustId"] = MyId.ToString();
            cookie.Expires   = DateTime.Now.AddDays(2);

            //Add it to the current web response
            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);

            //Navigate customer to home page
            System.Web.HttpContext.Current.Response.Redirect("Home.aspx");

            //Mail info to client
            SendSignUpMail();
        }
    }
예제 #52
0
        public override PanelStats GetPanelStats()
        {
            var pstats = new PanelStats();

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

                #region Disk Space
                using (MySqlCommand _cmd = new MySqlCommand(@"SELECT  CAST(SUM(httpdocs) AS SIGNED) as httpdocs, 
                                                                        CAST((SUM(mysql_dbases) + SUM(mssql_dbases)) AS SIGNED) as totaldbsize, 
                                                                        CAST(SUM(mailboxes) AS SIGNED) as totalmailboxsize, 
                                                                        CAST(SUM(subdomains) AS SIGNED) as subdomainsize 
                                                            FROM disk_usage", _conn))
                {
                    using (MySqlDataReader _read = _cmd.ExecuteReader())
                    {
                        while (_read.Read())
                        {
                            if (_read["httpdocs"] is System.Int64)
                            {
                                pstats.TotalDomainDiskSpace = Convert.ToDecimal(DataExtensions.GetColumnValue <System.Int64>(_read, "httpdocs"));
                            }
                            else
                            {
                                pstats.TotalDomainDiskSpace = DataExtensions.GetColumnValue <decimal>(_read, "httpdocs");
                            }

                            if (_read["totaldbsize"] is System.Int64)
                            {
                                pstats.TotalDatabaseDiskSpace = Convert.ToDecimal(DataExtensions.GetColumnValue <Int64>(_read, "totaldbsize"));
                            }
                            else
                            {
                                pstats.TotalDatabaseDiskSpace = DataExtensions.GetColumnValue <decimal>(_read, "totaldbsize");
                            }

                            if (_read["totalmailboxsize"] is System.Int64)
                            {
                                pstats.TotalEmailDiskSpace = Convert.ToDecimal(DataExtensions.GetColumnValue <Int64>(_read, "totalmailboxsize"));
                            }
                            else
                            {
                                pstats.TotalEmailDiskSpace = DataExtensions.GetColumnValue <decimal>(_read, "totalmailboxsize");
                            }

                            if (_read["subdomainsize"] is System.Int64)
                            {
                                pstats.TotalSubdomainDiskSpace = Convert.ToDecimal(DataExtensions.GetColumnValue <Int64>(_read, "subdomainsize"));
                            }
                            else
                            {
                                pstats.TotalSubdomainDiskSpace = DataExtensions.GetColumnValue <decimal>(_read, "subdomainsize");
                            }
                        }
                    }
                }
                #endregion

                #region Count
                using (MySqlCommand _cmd = new MySqlCommand(@"SELECT (SELECT COUNT(*) FROM domains) as domaincount, 
                                                                (SELECT COUNT(*) FROM mail) as mailcount, 
                                                                (SELECT COUNT(*) FROM clients) as resellercount, (SELECT COUNT(*) FROM data_bases) as databasecount, 
                                                                (SELECT COUNT(*) FROM domain_aliases) as aliascount, (SELECT COUNT(*) FROM subdomains) as subdomaincount", _conn))
                {
                    using (MySqlDataReader _read = _cmd.ExecuteReader())
                    {
                        while (_read.Read())
                        {
                            pstats.TotalDomainCount      = DataExtensions.GetColumnValue <long>(_read, "domaincount");
                            pstats.TotalEmailCount       = DataExtensions.GetColumnValue <long>(_read, "mailcount");
                            pstats.TotalResellerCount    = DataExtensions.GetColumnValue <long>(_read, "resellercount");
                            pstats.TotalDatabaseCount    = DataExtensions.GetColumnValue <long>(_read, "databasecount");
                            pstats.TotalDomainAliasCount = DataExtensions.GetColumnValue <long>(_read, "aliascount");
                            pstats.TotalSubdomainCount   = DataExtensions.GetColumnValue <long>(_read, "subdomaincount");
                        }
                    }
                }
                #endregion

                _conn.Close();
            }

            return(pstats);
        }
예제 #53
0
    /* Note: If customer Signs up successfully
     * Retrive all customer data with associated customer Id
     * i.e Troughout their name to what they ardered
     */
    public void DisplayCustomerData()
    {
        string selectSqlQueryCust = "SELECT  CustId, CustFirstName, CustLastName, CustMobNo,  CustEmailAddr, CustImg, CustShippingAddr, CustShipCountry, CustShipState, CustShipCity, CustShipPinCode, CustComment FROM customer";

        selectSqlQueryCust += "WHERE CustId = @CustId";

        MySqlConnection connection = new MySqlConnection(connectionString);

        MySqlCommand cmd;

        MySqlDataAdapter adaptor;

        MySqlDataReader reader;

        cmd = new MySqlCommand(selectSqlQueryCust, connection);

        //Add the paramaters
        cmd.Parameters.AddWithValue("@CustId", MyId);

        adaptor = new MySqlDataAdapter(cmd);

        try
        {
            //To automatically dispose the connction Obj
            using (connection)
            {
                // Open the database connection
                connection.Open();
                reader = cmd.ExecuteReader();

                //Read the data from Customer table
                //and Set the Customer's Object fields
                while (reader.Read())
                {
                    MyId = Convert.ToInt32(reader["CustId"]);

                    CustFirstName = reader["CustFirstName"].ToString();

                    CustLastName = reader["CustLastName"].ToString();

                    CustMobNo = Convert.ToInt32(reader["CustMobNo"]);

                    EmailId = reader["CustEmailAddr"].ToString();

                    CustImg = reader["CustImg"].ToString();

                    CustShippAddr = reader["CustShippingAddr"].ToString();

                    CustShipCountry = reader["CustShipCountry"].ToString();

                    CustShipState = reader["CustShipState"].ToString();

                    CustShipPinCode = Convert.ToInt32(reader["CustShipPinCode"]);

                    CustComment = reader["CustComment"].ToString();
                }
            }
        }

        catch (Exception error)
        {
            Label errorLbl = new Label();
            errorLbl.Text = error.ToString();
        }
    }
예제 #54
0
        public bool Insertar(BE_EST_CLIENTES e_Cliente)
        {
            bool          booOk      = false;
            int           n_row      = 0;
            DatosMySql    xMiFuncion = new DatosMySql();
            BE_MAE_CLIPRO e_cli      = new BE_MAE_CLIPRO();

            mysConec = xMiFuncion.ReAbrirConeccion(mysConec);

            e_cli.n_idemp     = 0; //e_Cliente.n_idemp;
            e_cli.n_id        = 0;
            e_cli.n_idcatemp  = 2;
            e_cli.n_idtipcon  = e_Cliente.n_idtipcon;
            e_cli.n_idtipdoc  = e_Cliente.n_idtipdocide;
            e_cli.c_numdoc    = e_Cliente.c_numdocide;
            e_cli.c_nombre    = e_Cliente.c_nom;
            e_cli.c_nomcli1   = e_Cliente.c_nom1;
            e_cli.c_nomcli2   = e_Cliente.c_nom2;
            e_cli.c_apecli1   = e_Cliente.c_ape1;
            e_cli.c_apecli2   = e_Cliente.c_ape2;
            e_cli.c_dir       = e_Cliente.c_dir;
            e_cli.c_tel       = e_Cliente.c_numtel;
            e_cli.c_fax       = "";
            e_cli.c_nomcon    = e_Cliente.c_nom;
            e_cli.c_email     = "";
            e_cli.c_pagweb    = "";
            e_cli.n_estado    = 1;
            e_cli.n_iddep     = e_Cliente.n_iddep;
            e_cli.n_idpro     = e_Cliente.n_idpro;
            e_cli.n_iddis     = e_Cliente.n_iddis;
            e_cli.n_ageret    = 0;
            e_cli.c_codcen    = "";
            e_cli.n_idven     = 0;
            e_cli.n_idcondpag = 0;
            e_cli.c_letnomgir = "";
            e_cli.c_letgirdir = "";
            e_cli.c_letnumdoc = "";
            e_cli.c_lettel    = "";
            e_cli.n_tipreg    = 1;
            e_cli.d_fchini    = e_Cliente.d_fching;
            //e_cli.n_ageper = 0;

            booOk = xMiFuncion.StoreEjecutar("mae_clipro_insertar", e_cli, mysConec, 0);
            if (booOk == true)
            {
                e_Cliente.n_id = Convert.ToInt32(xMiFuncion.intIdGenerado);
                booOk          = xMiFuncion.StoreEjecutar("est_clientes_insertar", e_Cliente, mysConec, null);

                if (booOk == true)
                {
                    for (n_row = 0; n_row <= l_ClientePlaca.Count - 1; n_row++)
                    {
                        l_ClientePlaca[n_row].n_idcli = e_Cliente.n_id;
                        if (xMiFuncion.StoreEjecutar("est_clientesplacas_insertar", l_ClientePlaca[n_row], mysConec, null) == false)
                        {
                            b_OcurrioError = xMiFuncion.booOcurrioError;
                            c_ErrorMensaje = xMiFuncion.StrErrorMensaje;
                            n_ErrorNumber  = xMiFuncion.IntErrorNumber;
                            return(booOk);
                        }
                    }

                    CD_est_otrocargoscab o_otrocab = new CD_est_otrocargoscab();
                    o_otrocab.mysConec = mysConec;
                    e_carcab.n_idcli   = e_Cliente.n_id;
                    if (o_otrocab.Insertar(e_carcab, l_cardet, 1) == true)
                    {
                        n_idcargogenerado = o_otrocab.n_idcargogenerado;
                    }
                    else
                    {
                        b_OcurrioError = o_otrocab.b_OcurrioError;
                        c_ErrorMensaje = o_otrocab.c_ErrorMensaje;
                        n_ErrorNumber  = o_otrocab.n_ErrorNumber;
                        return(booOk);
                    }

                    booOk = true;
                }
                else
                {
                    b_OcurrioError = xMiFuncion.booOcurrioError;
                    c_ErrorMensaje = xMiFuncion.StrErrorMensaje;
                    n_ErrorNumber  = xMiFuncion.IntErrorNumber;
                    return(booOk);
                }
            }
            else
            {
                b_OcurrioError = xMiFuncion.booOcurrioError;
                c_ErrorMensaje = xMiFuncion.StrErrorMensaje;
                n_ErrorNumber  = xMiFuncion.IntErrorNumber;
                return(booOk);
            }

            return(booOk);
        }
예제 #55
0
    public void UTF8PreparedAndUsingParameters()
    {
      if (st.Version < new Version(4, 1)) return;

      st.execSQL("DROP TABLE IF EXISTS Test");
      st.execSQL("CREATE TABLE Test (name VARCHAR(200) CHAR SET utf8)");

      using (MySqlConnection c = new MySqlConnection(st.conn.ConnectionString + ";charset=utf8"))
      {
        c.Open();

        MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES(?val)", c);
        cmd.Parameters.Add("?val", MySqlDbType.VarChar);
        cmd.Prepare();

        cmd.Parameters[0].Value = "ЁЄЉҖҚ";			// Russian
        cmd.ExecuteNonQuery();

        cmd.Parameters[0].Value = "兣冘凥凷冋";		// simplified Chinese
        cmd.ExecuteNonQuery();

        cmd.Parameters[0].Value = "困巫忘否役";		// traditional Chinese
        cmd.ExecuteNonQuery();

        cmd.Parameters[0].Value = "涯割晦叶角";		// Japanese
        cmd.ExecuteNonQuery();

        cmd.Parameters[0].Value = "ברחפע";			// Hebrew
        cmd.ExecuteNonQuery();

        cmd.Parameters[0].Value = "ψόβΩΞ";			// Greek
        cmd.ExecuteNonQuery();

        cmd.Parameters[0].Value = "þðüçöÝÞÐÜÇÖ";	// Turkish
        cmd.ExecuteNonQuery();

        cmd.Parameters[0].Value = "ฅๆษ";				// Thai
        cmd.ExecuteNonQuery();

        cmd.CommandText = "SELECT * FROM Test";
        using (MySqlDataReader reader = cmd.ExecuteReader())
        {
          reader.Read();
          Assert.Equal("ЁЄЉҖҚ", reader.GetString(0));
          reader.Read();
          Assert.Equal("兣冘凥凷冋", reader.GetString(0));
          reader.Read();
          Assert.Equal("困巫忘否役", reader.GetString(0));
          reader.Read();
          Assert.Equal("涯割晦叶角", reader.GetString(0));
          reader.Read();
          Assert.Equal("ברחפע", reader.GetString(0));
          reader.Read();
          Assert.Equal("ψόβΩΞ", reader.GetString(0));
          reader.Read();
          Assert.Equal("þðüçöÝÞÐÜÇÖ", reader.GetString(0));
          reader.Read();
          Assert.Equal("ฅๆษ", reader.GetString(0));
        }
      }
    }
예제 #56
0
        public static void getEvents()
        {
            U.log("Starting main event loop");

            var upl = new S3Uploader(U.config["S3Region"], U.config["S3Bucket"]);

            var basePath = U.config["ImgBasePath"];

            if (basePath.Substring(basePath.Length - 1) != "/")
            {
                basePath += "/";
            }

            var sleepSecs = U.config["LoopPauseSeconds"] ?? "3";



            var sleepMs = Convert.ToInt32(sleepSecs) * 1000;

            var lastNotifyTime = DateTime.Now.AddDays(-1);

            using (MySqlConnection connReader = new MySqlConnection(U.config["MySqlConnection"]))
                using (MySqlConnection connWriter = new MySqlConnection(U.config["MySqlConnection"]))
                {
                    while (true)
                    {
                        try
                        {
                            if (connReader.State != System.Data.ConnectionState.Open)
                            {
                                connReader.Open();
                            }

                            if (connWriter.State != System.Data.ConnectionState.Open)
                            {
                                connWriter.Open();
                            }
                            MySqlCommand cmd = new MySqlCommand(U.config["ZMQuery"], connReader);
                            //occassionally write out that we're running..
                            if ((DateTime.Now - lastNotifyTime).TotalSeconds > 120)
                            {
                                U.log("Checking for new events");
                                lastNotifyTime = DateTime.Now;
                            }
                            using (var reader = cmd.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    var e = new ZoneMinderEvent(Convert.ToInt64(reader["frameid"]), reader["monitor_name"].ToString());
                                    e.starttime = Convert.ToDateTime(reader["starttime"]);
                                    var img = new zmImage(e, U.config["ImgBasePath"], Convert.ToInt64(reader["eventid"]));
                                    if (File.Exists(img.fpath))
                                    {
                                        try
                                        {
                                            var s3Key = $"{e.monitorName}/{e.starttime.Year}/{e.starttime.Month.ToString().PadLeft(2, '0')}/{e.starttime.Day.ToString().PadLeft(2, '0')}/{e.starttime.Hour.ToString().PadLeft(2, '0')}-{e.starttime.Minute.ToString().PadLeft(2, '0')}";



                                            //fire and forget here..
                                            upl.uploadFile(img.fpath, s3Key);

                                            // update to mark them as uploaded
                                            var          sql          = $"insert alarm_uploaded (frameid,upload_timestamp,eventid) values ( {e.frameID}, CURRENT_TIMESTAMP, {img.eventId})";
                                            MySqlCommand insertCmd    = new MySqlCommand(sql, connWriter);
                                            var          rowsAffected = insertCmd.ExecuteNonQuery();
                                            if (rowsAffected <= 0)
                                            {
                                                U.log("Did not insert a row into alarm_uploaded");
                                            }
                                        }
                                        catch (Exception exc)
                                        {
                                            U.log("Error uploading/updating db", exc);
                                        }
                                    }
                                    else
                                    {
                                        U.log("File does not exist - " + img.fpath);
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            U.log("Error in outer loop", e);
                        }
                        System.Threading.Thread.Sleep(sleepMs);
                    }
                }
            //return list;
        }
예제 #57
0
        private void textBoxKeres_TextChanged(object sender, EventArgs e)
        {
            MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;username=root;password=;database=watch_men_db");

            if (comboBoxKategoria.Text == "ID")
            {
                MySqlDataAdapter      adapter = new MySqlDataAdapter("SELECT `ID`, `cikk_szam`, `marka`, `tipus`, `Netto_ar`, `Afa_kulcs`, `Brutto_ar`,`Darabszam`,`nem`,`szerkezet`,`kijelzes`,`tok_szine`,`szij_anyaga` FROM `orak` WHERE ID LIKE '" + textBoxKeres.Text + "%'", connection);
                System.Data.DataTable table   = new System.Data.DataTable();
                adapter.Fill(table);
                dataGridViewOra.DataSource = table;
            }
            else if (comboBoxKategoria.Text == "Cikkszám")
            {
                MySqlDataAdapter      adapter = new MySqlDataAdapter("SELECT `ID`, `cikk_szam`, `marka`, `tipus`, `Netto_ar`, `Afa_kulcs`, `Brutto_ar`,`Darabszam`,`nem`,`szerkezet`,`kijelzes`,`tok_szine`,`szij_anyaga` FROM `orak` WHERE cikk_szam LIKE '" + textBoxKeres.Text + "%'", connection);
                System.Data.DataTable table   = new System.Data.DataTable();
                adapter.Fill(table);
                dataGridViewOra.DataSource = table;
            }
            else if (comboBoxKategoria.Text == "Márka")
            {
                MySqlDataAdapter      adapter = new MySqlDataAdapter("SELECT `ID`, `cikk_szam`, `marka`, `tipus`, `Netto_ar`, `Afa_kulcs`, `Brutto_ar`,`Darabszam`,`nem`,`szerkezet`,`kijelzes`,`tok_szine`,`szij_anyaga` FROM `orak` WHERE marka LIKE '" + textBoxKeres.Text + "%'", connection);
                System.Data.DataTable table   = new System.Data.DataTable();
                adapter.Fill(table);
                dataGridViewOra.DataSource = table;
            }
            else if (comboBoxKategoria.Text == "Típus")
            {
                MySqlDataAdapter      adapter = new MySqlDataAdapter("SELECT `ID`, `cikk_szam`, `marka`, `tipus`, `Netto_ar`, `Afa_kulcs`, `Brutto_ar`,`Darabszam`,`nem`,`szerkezet`,`kijelzes`,`tok_szine`,`szij_anyaga` FROM `orak` WHERE tipus LIKE '" + textBoxKeres.Text + "%'", connection);
                System.Data.DataTable table   = new System.Data.DataTable();
                adapter.Fill(table);
                dataGridViewOra.DataSource = table;
            }
            else if (comboBoxKategoria.Text == "Nettóár")
            {
                MySqlDataAdapter      adapter = new MySqlDataAdapter("SELECT `ID`, `cikk_szam`, `marka`, `tipus`, `Netto_ar`, `Afa_kulcs`, `Brutto_ar`,`Darabszam`,`nem`,`szerkezet`,`kijelzes`,`tok_szine`,`szij_anyaga` FROM `orak` WHERE Netto_ar LIKE '" + textBoxKeres.Text + "%'", connection);
                System.Data.DataTable table   = new System.Data.DataTable();
                adapter.Fill(table);
                dataGridViewOra.DataSource = table;
            }
            else if (comboBoxKategoria.Text == "Bruttóár")
            {
                MySqlDataAdapter      adapter = new MySqlDataAdapter("SELECT `ID`, `cikk_szam`, `marka`, `tipus`, `Netto_ar`, `Afa_kulcs`, `Brutto_ar`,`Darabszam`,`nem`,`szerkezet`,`kijelzes`,`tok_szine`,`szij_anyaga` FROM `orak` WHERE Brutto_ar LIKE '" + textBoxKeres.Text + "%'", connection);
                System.Data.DataTable table   = new System.Data.DataTable();
                adapter.Fill(table);
                dataGridViewOra.DataSource = table;
            }
            else if (comboBoxKategoria.Text == "Nem")
            {
                MySqlDataAdapter      adapter = new MySqlDataAdapter("SELECT `ID`, `cikk_szam`, `marka`, `tipus`, `Netto_ar`, `Afa_kulcs`, `Brutto_ar`,`Darabszam`,`nem`,`szerkezet`,`kijelzes`,`tok_szine`,`szij_anyaga` FROM `orak` WHERE nem LIKE '" + textBoxKeres.Text + "%'", connection);
                System.Data.DataTable table   = new System.Data.DataTable();
                adapter.Fill(table);
                dataGridViewOra.DataSource = table;
            }
            else if (comboBoxKategoria.Text == "Szerkezet")
            {
                MySqlDataAdapter      adapter = new MySqlDataAdapter("SELECT `ID`, `cikk_szam`, `marka`, `tipus`, `Netto_ar`, `Afa_kulcs`, `Brutto_ar`,`Darabszam`,`nem`,`szerkezet`,`kijelzes`,`tok_szine`,`szij_anyaga` FROM `orak` WHERE szerkezet LIKE '" + textBoxKeres.Text + "%'", connection);
                System.Data.DataTable table   = new System.Data.DataTable();
                adapter.Fill(table);
                dataGridViewOra.DataSource = table;
            }
            else if (comboBoxKategoria.Text == "Kijelzés")
            {
                MySqlDataAdapter      adapter = new MySqlDataAdapter("SELECT `ID`, `cikk_szam`, `marka`, `tipus`, `Netto_ar`, `Afa_kulcs`, `Brutto_ar`,`Darabszam`,`nem`,`szerkezet`,`kijelzes`,`tok_szine`,`szij_anyaga` FROM `orak` WHERE kijelzes LIKE '" + textBoxKeres.Text + "%'", connection);
                System.Data.DataTable table   = new System.Data.DataTable();
                adapter.Fill(table);
                dataGridViewOra.DataSource = table;
            }
            else if (comboBoxKategoria.Text == "Tokszíne")
            {
                MySqlDataAdapter      adapter = new MySqlDataAdapter("SELECT `ID`, `cikk_szam`, `marka`, `tipus`, `Netto_ar`, `Afa_kulcs`, `Brutto_ar`,`Darabszam`,`nem`,`szerkezet`,`kijelzes`,`tok_szine`,`szij_anyaga` FROM `orak` WHERE tok_szine LIKE '" + textBoxKeres.Text + "%'", connection);
                System.Data.DataTable table   = new System.Data.DataTable();
                adapter.Fill(table);
                dataGridViewOra.DataSource = table;
            }
            else if (comboBoxKategoria.Text == "Szíjanyaga")
            {
                MySqlDataAdapter      adapter = new MySqlDataAdapter("SELECT `ID`, `cikk_szam`, `marka`, `tipus`, `Netto_ar`, `Afa_kulcs`, `Brutto_ar`,`Darabszam`,`nem`,`szerkezet`,`kijelzes`,`tok_szine`,`szij_anyaga` FROM `orak` WHERE szij_anyaga LIKE '" + textBoxKeres.Text + "%'", connection);
                System.Data.DataTable table   = new System.Data.DataTable();
                adapter.Fill(table);
                dataGridViewOra.DataSource = table;
            }
        }
예제 #58
0
        public override List <Domain> GetDomains()
        {
            var tmp = new List <Domain>();

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

                using (MySqlCommand _cmd = new MySqlCommand(@"SELECT 
                                                                    domains.id, 
                                                                    domains.name, 
                                                                    hosting.fp_adm, 
                                                                    accounts.password, 
                                                                    clients.login, 
                                                                    clients.passwd, 
                                                                    dom_level_usrs.passwd As DomainPass, 
                                                                    domains.status As Status, 
                                                                    limits.value as expiration,
                                                                    domains.htype
			                                            FROM domains 
                                                LEFT JOIN hosting ON hosting.dom_id = domains.id 
				                                LEFT JOIN sys_users ON hosting.sys_user_id = sys_users.id 
				                                LEFT JOIN accounts ON accounts.id = sys_users.account_id 
				                                LEFT JOIN clients ON clients.id = domains.cl_id 
				                                LEFT JOIN dom_level_usrs ON dom_level_usrs.dom_id = domains.id 
                                                LEFT JOIN limits ON limits.id = domains.limits_id AND limits.limit_name = 'expiration'", _conn))
                {
                    using (MySqlDataReader _read = _cmd.ExecuteReader())
                    {
                        while (_read.Read())
                        {
                            var _d = new Domain();
                            _d.Id             = Convert.ToInt32(DataExtensions.GetColumnValue <uint>(_read, "id"));
                            _d.Name           = DataExtensions.GetColumnValue <String>(_read, "name").ToLower();
                            _d.ClientName     = DataExtensions.GetColumnValue <String>(_read, "login");
                            _d.DomainPassword = DataExtensions.GetColumnValue <String>(_read, "DomainPass");

                            _d.Username = DataExtensions.GetColumnValue <String>(_read, "fp_adm");
                            _d.Password = DataExtensions.GetColumnValue <String>(_read, "password");

                            if (String.IsNullOrEmpty(_d.Username))
                            {
                                _d.Username = _d.Name;
                            }

                            if (String.IsNullOrEmpty(_d.Password))
                            {
                                _d.Password = DataHelper.GetPassword();
                            }

                            _d.Status = Convert.ToInt64(DataExtensions.GetColumnValue <ulong>(_read, "Status"));
                            var expirationString = String.Empty;

                            if (_read["expiration"] is System.Int64)
                            {
                                expirationString = DataExtensions.GetColumnValue <Int64>(_read, "expiration").ToString();
                            }
                            else
                            {
                                expirationString = DataExtensions.GetColumnValue <string>(_read, "expiration");
                            }

                            var expirationUnitTime = String.IsNullOrEmpty(expirationString) ? -1D : Convert.ToDouble(expirationString);
                            if (expirationUnitTime != -1)
                            {
                                _d.Expiration = DataHelper.UnixTimeStampToDateTime(expirationUnitTime);
                            }

                            var hostingType = DataExtensions.GetColumnValue <String>(_read, "htype");
                            _d.isForwarding = (hostingType == "std_fwd" || hostingType == "frm_fwd");

                            if (_d.isForwarding)
                            {
                                var frw = GetForwarding(_d.Name);
                                _d.ForwardUrl = frw.ForwardUrl;
                            }

                            _d.Aliases    = GetDomainAliases(_d.Name);
                            _d.Databases  = GetDatabases(_d.Name);
                            _d.Limits     = GetDomainLimits(_d.Name);
                            _d.Subdomains = GetSubdomains(_d.Name);
                            _d.Zone       = GetDnsZone(_d.Name);
                            _d.Emails     = GetEmails(_d.Name);

                            tmp.Add(_d);
                        }
                    }
                }
                _conn.Close();
            }

            return(tmp);
        }
예제 #59
0
        }//end AgregarUsuario

        /// <summary>
        /// login
        /// </summary>
        /// <param name="usu"></param>
        /// <returns></returns>
        public int ObtenerUsuario(string usuarioNombre, string usuarioPasword, string usuarioRol)
        {
            int             uARetornar = -2;
            MySqlConnection conexion   = null;
            MySqlDataReader reader     = null;

            try
            {
                conexion = ConexionDB.GetConexion();
                conexion.Open();
                //nombre
                string sql = @"select idUsuarios, password, rol
                                from usuarios 
                                where nombre=@nombre  
                                and estado='activo'";

                /*string sql = @"select idUsuarios, nombre, password,
                 *          from usuarios where nombre=@nombre and password=@password";*/
                MySqlCommand comando = new MySqlCommand(sql, conexion);
                comando.Parameters.AddWithValue("@nombre", usuarioNombre);
                //comando.Parameters.AddWithValue("@password", usuarioPasword);
                reader = comando.ExecuteReader();
                //si hay por lo menos una fila entra
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        int id = reader.GetInt32(0);
                        //string nombre = (reader[1] != DBNull.Value) ? reader.GetString(1) : "";
                        string password = (reader[1] != DBNull.Value) ? reader.GetString(1) : "";
                        string rol      = (reader[2] != DBNull.Value) ? reader.GetString(2) : "";
                        if ((rol == usuarioRol || rol == "admin") && password == usuarioPasword)
                        {
                            uARetornar = id;
                        }
                        //string password = (reader[2] != DBNull.Value) ? reader.GetString(2) : "";
                        //string rol = (reader[3] != DBNull.Value) ? reader.GetString(2) : "";
                        //if (usuarioRol==)
                    }
                }
            }
            catch (MySqlException ex)
            {
                string mensaje = ex.ToString();
                Console.WriteLine("Error: " + mensaje);
                uARetornar = -1;
            }
            finally
            {
                /**/ if (conexion != null)
                {
                    conexion.Close();
                    conexion.Dispose();
                }
                if (reader != null)
                {
                    reader.Close();
                    conexion.Dispose();
                }
            }
            return(uARetornar);
        } //end
예제 #60
0
        private void buttonUbah_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtNamaProduk.Text.Trim()))
            {
                MessageBox.Show("Nama Produk Tidak Boleh Kosong");
                throw null;
            }
            if (string.IsNullOrEmpty(txtStok.Text.Trim()))
            {
                MessageBox.Show("Stok Tidak Boleh Kosong");
                throw null;
            }
            if (string.IsNullOrEmpty(txtStokMinimal.Text.Trim()))
            {
                MessageBox.Show("Stok Minimal Tidak Boleh Kosong");
                throw null;
            }
            if (string.IsNullOrEmpty(txtSatuanProduk.Text.Trim()))
            {
                MessageBox.Show("Satuan Produk Tidak Boleh Kosong");
                throw null;
            }
            if (!Regex.Match(txtSatuanProduk.Text, @"^[a-zA-Z]+$").Success)
            {
                MessageBox.Show("Satuan Produk Tidak Boleh Mengandung Angka");
                throw null;
            }
            if (string.IsNullOrEmpty(txtHargaBeli.Text.Trim()))
            {
                MessageBox.Show("Harga Beli Tidak Boleh Kosong");
                throw null;
            }
            if (string.IsNullOrEmpty(txtHargaJual.Text.Trim()))
            {
                MessageBox.Show("Harga Jual Tidak Boleh Kosong");
                throw null;
            }
            if (pictureBoxProduk.Image == null)
            {
                MessageBox.Show("Gambar Tidak Boleh Kosong");
                throw null;
            }
            ValidateNumberOnly(txtStok.Text);
            ValidateNumberOnly(txtStokMinimal.Text);
            ValidateNumberOnly(txtHargaBeli.Text);
            ValidateNumberOnly(txtHargaJual.Text);

            MemoryStream ms = new MemoryStream();

            pictureBoxProduk.Image.Save(ms, pictureBoxProduk.Image.RawFormat);
            byte[] img = ms.ToArray();

            string          connStr = "datasource=127.0.0.1;port=3306;username=root;password=;database=kouvee;Convert Zero Datetime=True;";
            MySqlConnection conn    = new MySqlConnection(connStr);
            MySqlCommand    cmd;
            String          updateQuery = "UPDATE produk SET ID_PEGAWAI = @ID_PEGAWAI, NAMA_PRODUK = @NAMA_PRODUK, STOCK = @STOCK, MIN_STOCK = @MIN_STOCK, " +
                                          "SATUAN_PRODUK = @SATUAN_PRODUK, HARGA_BELI = @HARGA_BELI, HARGA_JUAL = @HARGA_JUAL, GAMBAR_BLOB = @GAMBAR_BLOB " +
                                          "WHERE NAMA_PRODUK = '" + txtCari.Text + "';";


            conn.Open();
            cmd = new MySqlCommand(updateQuery, conn);
            cmd.Parameters.Add("@ID_PEGAWAI", MySqlDbType.Int32).Value       = FormLogin.id_pegawai;
            cmd.Parameters.Add("@NAMA_PRODUK", MySqlDbType.VarChar).Value    = txtNamaProduk.Text;
            cmd.Parameters.Add("@STOCK", MySqlDbType.Int32).Value            = Int32.Parse(txtStok.Text);
            cmd.Parameters.Add("@MIN_STOCK", MySqlDbType.Int32).Value        = Int32.Parse(txtStokMinimal.Text);
            cmd.Parameters.Add("@SATUAN_PRODUK", MySqlDbType.VarChar).Value  = txtSatuanProduk.Text;
            cmd.Parameters.Add("@HARGA_BELI", MySqlDbType.Int32).Value       = Int32.Parse(txtHargaBeli.Text);
            cmd.Parameters.Add("@HARGA_JUAL", MySqlDbType.Int32).Value       = Int32.Parse(txtHargaJual.Text);
            cmd.Parameters.Add("@GAMBAR_BLOB", MySqlDbType.MediumBlob).Value = img;
            cmd.ExecuteReader();
            MessageBox.Show("Data Berhasil Diubah");

            conn.Close();

            txtNamaProduk.Enabled   = false;
            txtStok.Enabled         = false;
            txtStokMinimal.Enabled  = false;
            txtSatuanProduk.Enabled = false;
            txtHargaBeli.Enabled    = false;
            txtHargaJual.Enabled    = false;
            txtGambar.Enabled       = false;
            buttonUbah.Enabled      = false;
            btnBrowseGambar.Enabled = false;
        }