public static bool validateLogin(UserLog ul) { DBConnector dbcon = new DBConnector(); dbcon.openConnection(); //try { MySqlCommand cmd = new MySqlCommand(); cmd.CommandText = "SELECT * FROM user WHERE username='******' AND password=MD5('" + ul.getPassword() + "')"; cmd.Connection = dbcon.connection; MySqlDataReader login = cmd.ExecuteReader(); if (login.Read()) { LoginSession.setSession(login.GetString("iduser")); //login.Close(); dbcon.closeConnection(); return true; } else { //login.Close(); dbcon.closeConnection(); return false; } //} //catch (MySqlException e){ //int errorcode = e.Number; //return false; //} }
private void cartelera_Load(object sender, EventArgs e) { //frmCiudad ciudad = new frmCiudad(); String numeroSucursal = lblsucursal.Text; string query = string.Format("select TRHORA.idSucursal,MAPELI.iidpelicula, MAPELI.bimagen FROM TRHORARIO TRHORA, MAPELICULA MAPELI WHERE TRHORA.iidpelicula=MAPELI.iidpelicula and TRHORA.idSucursal = '"+ numeroSucursal +"'"); MySqlCommand comando = new MySqlCommand(query, classCrearConexion.Conexion()); MySqlDataAdapter da = new MySqlDataAdapter(comando); DataSet ds = new DataSet("MAPELICULA"); da.Fill(ds, "MAPELICULA"); byte[] datos = new byte[0]; DataRow dr = ds.Tables["MAPELICULA"].Rows[0]; datos = (byte[])dr["bimagen"]; System.IO.MemoryStream ms = new System.IO.MemoryStream(datos); pb1.Image = System.Drawing.Bitmap.FromStream(ms); /*pb1.Image = Properties.Resources.El_Destino_de_Júpite; pb1.Refresh(); pb2.Image = Properties.Resources.FF2; pb2.Refresh(); pb3.Image = Properties.Resources.In_to_the_Woods_En_el_Bosqu; pb3.Refresh(); pb4.Image = Properties.Resources.Ombis_Alien_Invasion__2015_; pb4.Refresh(); pb5.Image = Properties.Resources.peliculas_2015_15_e1422754101215; pb5.Refresh(); pb6.Image = Properties.Resources.peliculas_2015_rapido_furioso_4; pb6.Refresh(); pb7.Image = Properties.Resources.images; pb7.Refresh();*/ }
/// <summary> /// 修改数据 /// </summary> /// <param name="entity"></param> /// <returns></returns> public int Update(Policy entity) { string sql = "UPDATE tb_policy SET agentType=@agentType,subject=@subject,content=@content,sender=@sender,attachment=@attachment,attachmentName=@attachmentName,creatTime=@creatTime,"; sql = sql + " type=@type,validateStartTime=@validateStartTime,validateEndTime=@validateEndTime,isValidate=@isValidate,isDelete=@isDelete,deleteTime=@deleteTime,toAll=@toAll where sequence=@sequence "; //string sql = "UPDATE cimuser SET userNickName=@userNickName WHERE userid=@userid"; using (MySqlConnection mycn = new MySqlConnection(mysqlConnection)) { mycn.Open(); MySqlCommand command = new MySqlCommand(sql, mycn); command.Parameters.AddWithValue("@agentType", entity.agentType); command.Parameters.AddWithValue("@sequence", entity.sequence); command.Parameters.AddWithValue("@subject", entity.subject); command.Parameters.AddWithValue("@content", entity.content); command.Parameters.AddWithValue("@sender", entity.sender); command.Parameters.AddWithValue("@attachment", entity.attachment); command.Parameters.AddWithValue("@attachmentName", entity.attachmentName); command.Parameters.AddWithValue("@creatTime", entity.creatTime); command.Parameters.AddWithValue("@type", entity.type); command.Parameters.AddWithValue("@validateStartTime", entity.validateStartTime); command.Parameters.AddWithValue("@validateEndTime", entity.validateEndTime); command.Parameters.AddWithValue("@isValidate", entity.isValidate); command.Parameters.AddWithValue("@isDelete", entity.isDelete); command.Parameters.AddWithValue("@deleteTime", entity.deleteTime); command.Parameters.AddWithValue("@toAll", entity.toAll); int i = command.ExecuteNonQuery(); mycn.Close(); mycn.Dispose(); return i; } }
public Account LoadAccount(string username) { string SqlQuery = "SELECT * FROM `accounts` WHERE `username` = ?username"; MySqlCommand SqlCommand = new MySqlCommand(SqlQuery, AccountDAOConnection); SqlCommand.Parameters.AddWithValue("?username", username); MySqlDataReader AccountReader = SqlCommand.ExecuteReader(); Account acc = new Account(); if (AccountReader.HasRows) { while (AccountReader.Read()) { acc.AccountId = AccountReader.GetInt32(0); acc.Username = AccountReader.GetString(1); acc.Password = AccountReader.GetString(2); acc.Email = AccountReader.GetString(3); acc.AccessLevel = (byte)AccountReader.GetInt32(4); acc.Membership = (byte)AccountReader.GetInt32(5); acc.isGM = AccountReader.GetBoolean(6); acc.LastOnlineUtc = AccountReader.GetInt64(7); acc.Coins = (int)AccountReader.GetInt32(8); acc.Ip = AccountReader.GetString(9); acc.UiSettings = ByteUtilities.StringToByteArray(AccountReader.GetString(10)); } } AccountReader.Close(); return (acc.Username == "") ? null : acc; }
public Int16 Insert(ParkingRateDetails Details) { try { Details.CreatedByName = Details.ParkingRateID == 0 ? Details.CreatedByName : Details.LastUpdatedByName; Save(Details); string SQL = "SELECT LAST_INSERT_ID();"; MySqlCommand cmd = new MySqlCommand(); cmd.CommandType = System.Data.CommandType.Text; cmd.CommandText = SQL; System.Data.DataTable dt = new System.Data.DataTable("LAST_INSERT_ID"); base.MySqlDataAdapterFill(cmd, dt); Int16 iID = 0; foreach (System.Data.DataRow dr in dt.Rows) { iID = Int16.Parse(dr[0].ToString()); } return iID; } catch (Exception ex) { throw base.ThrowException(ex); } }
public static Models.AccountsModel LoadAccount(int accountID) { DatabaseProvider.CheckConnection(); lock (DatabaseProvider.ConnectionLocker) { var account = new Models.AccountsModel(); var sqlText = "SELECT * FROM dyn_accounts WHERE id=@id"; var sqlCommand = new MySqlCommand(sqlText, DatabaseProvider.Connection); sqlCommand.Parameters.Add(new MySqlParameter("@id", accountID)); var sqlReader = sqlCommand.ExecuteReader(); if (sqlReader.Read()) { account.ID = sqlReader.GetInt16("id"); account.Username = sqlReader.GetString("username"); account.Password = sqlReader.GetString("password"); account.Pseudo = sqlReader.GetString("pseudo"); account.Communauty = sqlReader.GetInt16("communauty"); account.Level = sqlReader.GetInt16("gmLevel"); account.Question = sqlReader.GetString("question"); account.Answer = sqlReader.GetString("answer"); account.SubscriptionDate = sqlReader.GetDateTime("subscription"); } sqlReader.Close(); return account; } }
public int InserirPedido(int numCliente, List<Item> pedido) { int NumPedido = 0; int idPedido = 0; MySqlConnection conn = new MySqlConnection(connectionString); MySqlCommand cmd = new MySqlCommand(); cmd.Connection = conn; conn.Open(); cmd.CommandText = "Select Max(numero) + 1 from tb_Pedidos"; NumPedido = int.Parse(cmd.ExecuteScalar().ToString()); cmd.CommandText = "Insert into tb_Pedidos (numero, id_cliente, data) Values(" + NumPedido + "," + numCliente + ", sysdate()); select Max(id) from tb_Pedidos;"; idPedido = int.Parse(cmd.ExecuteScalar().ToString()); foreach (Item item in pedido) { cmd.CommandText = "insert into tb_items (nome, descricao, preco, quantidade, id_pedido, urlImagem) Values ('" + item.descricao + "', Null,"+ item.preco.ToString().Replace(",",".") + "," + item.quantidade + "," + idPedido + ", Null);"; cmd.ExecuteNonQuery(); } conn.Close(); return NumPedido; }
public static List<Trayecto> buscarOrigenes() { List<Trayecto> trayectos = new List<Trayecto>(); ; MySqlConnection con = conexionDB.ObtenerConexion(); try { string sql = "select id, origen, destino, precio from trayecto group by origen"; MySqlCommand cmd = new MySqlCommand(sql, con); MySqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { trayectos.Add(new Trayecto(dr.GetInt32(0), CiudadFacade.buscarPorId(dr.GetInt32(1)), CiudadFacade.buscarPorId(dr.GetInt32(2)), dr.GetInt32(3))); } dr.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { con.Close(); } return trayectos; }
protected void Button_click(object sender, EventArgs e) { MySqlConnection bazaPovezava = new MySqlConnection(bazaConnString); try { bazaPovezava.Open(); string SQLcommand = "INSERT INTO User(username, firstname, lastname, password, email, city, country) VALUES(?un, ?fn, ?ln, ?pw, ?em, ?ci, ?co);"; MySqlCommand bazaUkaz = new MySqlCommand(SQLcommand, bazaPovezava); bazaUkaz.Parameters.Add(new MySqlParameter("?un", username.Text)); bazaUkaz.Parameters.Add(new MySqlParameter("?fn", firstname.Text)); bazaUkaz.Parameters.Add(new MySqlParameter("?ln", surname.Text)); bazaUkaz.Parameters.Add(new MySqlParameter("?pw", pass.Text)); bazaUkaz.Parameters.Add(new MySqlParameter("?em", email.Text)); bazaUkaz.Parameters.Add(new MySqlParameter("?ci", city.Text)); bazaUkaz.Parameters.Add(new MySqlParameter("?co", country.Text)); bazaUkaz.ExecuteNonQuery(); } catch(Exception ex) { Console.WriteLine(ex); } finally { bazaPovezava.Close(); } }
public static void LoadItemsSets() { lock (DatabaseHandler.ConnectionLocker) { var sqlText = "SELECT * FROM datas_items_sets"; var sqlCommand = new MySqlCommand(sqlText, DatabaseHandler.Connection); var sqlReader = sqlCommand.ExecuteReader(); while (sqlReader.Read()) { var set = new Models.Items.SetModel(); set.ID = sqlReader.GetInt16("ID"); set.ParseBonus(sqlReader.GetString("bonus")); set.ParseItems(sqlReader.GetString("items")); lock(SetsList) SetsList.Add(set); } sqlReader.Close(); } Utilities.Loggers.StatusLogger.Write(string.Format("Loaded @'{0}' items sets@ from the database !", SetsList.Count)); }
public static Trayecto buscarPorId(int id) { Trayecto trayecto = null; if (id > -1) { MySqlConnection con = conexionDB.ObtenerConexion(); try { string sql = "select id, origen, destino, precio from trayecto where id = " + id; MySqlCommand cmd = new MySqlCommand(sql, con); MySqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { trayecto = new Trayecto(dr.GetInt32(0), CiudadFacade.buscarPorId(dr.GetInt32(1)), CiudadFacade.buscarPorId(dr.GetInt32(2)), dr.GetInt32(3)); } dr.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); trayecto = null; } finally { con.Close(); } } return trayecto; }
public void create() { db = new Database(); if (officeVerification()) { try { officeQuery = new MySqlCommand(); officeQuery.Connection = db.Connection(); officeQuery.CommandText = "INSERT INTO office(officedescription) VALUES(@Description)"; officeQuery.Prepare(); officeQuery.Parameters.AddWithValue("@Description", officedescription); officeQuery.ExecuteNonQuery(); MessageBox.Show("A Descrição Cargo Assinatura " + officedescription + " foi criada com sucesso."); } catch (MySqlException ex) { MessageBox.Show("Ocurreu um erro"); Console.WriteLine("Error: {0}", ex.ToString()); } finally { db.Close(); } } }
public static void LoadItems() { lock (DatabaseHandler.ConnectionLocker) { var sqlText = "SELECT * FROM datas_items"; var sqlCommand = new MySqlCommand(sqlText, DatabaseHandler.Connection); var sqlReader = sqlCommand.ExecuteReader(); while (sqlReader.Read()) { var item = new Models.Items.ItemModel(); item.ID = sqlReader.GetInt32("ID"); item.Pods = sqlReader.GetInt16("Weight"); item.Price = sqlReader.GetInt32("Price"); item.Type = sqlReader.GetInt16("Type"); item.Level = sqlReader.GetInt16("Level"); item.Jet = sqlReader.GetString("Stats"); item.Condistr = sqlReader.GetString("Conditions"); item.ParseWeaponInfos(sqlReader.GetString("WeaponInfo")); item.ParseRandomJet(); lock(ItemsList) ItemsList.Add(item); } sqlReader.Close(); } Utilities.Loggers.StatusLogger.Write(string.Format("Loaded @'{0}' items@ from the database !", ItemsList.Count)); }
public string GetSchedule(string phone, string ordernum) { con.Open(); MySqlCommand cmd = new MySqlCommand("select TechnicianName, Phone, sdate,slotnumber,idtechnician,order_id from fosimple.technician t join fosimple.schedule s on s.technician_id = t.idTechnician join fosimple.orders o on o.idorders =s.order_id where idorders = " + ordernum + " and mobilenumber = '" + phone + "'", con); MySqlDataReader dr = cmd.ExecuteReader(); string techname = "", ph = "", sdate = "", slot = ""; int tid = 0; if (dr.Read()) { techname = dr[0].ToString(); ph = dr[1].ToString(); sdate = dr[2].ToString(); slot = dr[3].ToString(); // tid = Convert.ToInt16(dr[4].ToString()); } if(sdate != "") { if (Convert.ToDateTime(sdate) < DateTime.Now) { techname = "Completed"; } sdate = Convert.ToDateTime(sdate).Month.ToString() + "/" + Convert.ToDateTime(sdate).Day.ToString() + "/" + Convert.ToDateTime(sdate).Year.ToString(); } dr.Dispose(); con.Close(); return techname + "##" + ph + "##" + sdate + "##" + slot; }
public void addEntry(TrackingEntry entry) { MySqlCommand cmd = new MySqlCommand(); cmd.Connection = connection; cmd.CommandText = "INSERT INTO tracking_entry VALUES (NULL, @taggerID, @type, @isTagged," + " @taggerName, @entryDate, @tagNumber, @species, @city, @state, @country," + " @longitude, @latitude, @temperature, @precipitation, @windSpeed," + " @windDirection);"; cmd.Prepare(); cmd.Parameters.AddWithValue("@taggerID", entry.taggerID); cmd.Parameters.AddWithValue("@type", entry.type); cmd.Parameters.AddWithValue("@isTagged", entry.isTagged); cmd.Parameters.AddWithValue("@taggerName", entry.taggerName); cmd.Parameters.AddWithValue("@entryDate", entry.entryDate); cmd.Parameters.AddWithValue("@tagNumber", entry.tagNumber); cmd.Parameters.AddWithValue("@species", entry.species); cmd.Parameters.AddWithValue("@city", entry.city); cmd.Parameters.AddWithValue("@state", entry.state); cmd.Parameters.AddWithValue("@country", entry.country); cmd.Parameters.AddWithValue("@longitude", entry.longitude); cmd.Parameters.AddWithValue("@latitude", entry.latitude); cmd.Parameters.AddWithValue("@temperature", entry.temperature); cmd.Parameters.AddWithValue("@precipitation", entry.precipitation); cmd.Parameters.AddWithValue("@windSpeed", entry.windSpeed); cmd.Parameters.AddWithValue("@windDirection", entry.windDirection); cmd.ExecuteNonQuery(); }
public EditAlat(Alat alat) { InitializeComponent(); this.alat = alat; status = new List<KV>(); status.Add(new KV("Baik", 1)); status.Add(new KV("Rusak", 0)); comboBox_Status.ItemsSource = status; comboBox_Status.DisplayMemberPath = "Key"; comboBox_Status.SelectedValuePath = "Value"; comboBox_Status.SelectedValue = (alat.KondisiAlat) ? 1 : 0; textbox_Laboratorium.Text = alat.Lokasi; string query = "SELECT * FROM master_inventory_type"; using (MySqlCommand cmd = new MySqlCommand(query, db.ConnectionManager.Connection)) { try { DataTable dataSet = new DataTable(); using (MySqlDataAdapter dataAdapter = new MySqlDataAdapter(cmd)) { dataAdapter.Fill(dataSet); comboBox_Jenis_Barang.ItemsSource = dataSet.DefaultView; comboBox_Jenis_Barang.DisplayMemberPath = dataSet.Columns["nama"].ToString(); comboBox_Jenis_Barang.SelectedValuePath = dataSet.Columns["id"].ToString(); comboBox_Jenis_Barang.SelectedValue = alat.IdJenis; } } catch (MySql.Data.MySqlClient.MySqlException ex) { MessageBox.Show(ex.Message); } } }
public const string mysqlConnection = DBConstant.mysqlConnection;//"User Id=root;Host=115.29.229.134;Database=chinaunion;password=c513324665;charset=utf8"; /// <summary> /// 添加数据 /// </summary> /// <returns></returns> public int Add(Policy entity) { string sql = "INSERT INTO tb_policy (agentType,subject,content,sender,attachment,attachmentName,creatTime,type, validateStartTime,validateEndTime, isValidate, isDelete, deleteTime,toAll) VALUE (@agentType,@subject,@content,@sender,@attachment,@attachmentName,@creatTime,@type, @validateStartTime,@validateEndTime, @isValidate, @isDelete, @deleteTime,@toAll)"; using (MySqlConnection mycn = new MySqlConnection(mysqlConnection)) { mycn.Open(); MySqlCommand command = new MySqlCommand(sql, mycn); command.Parameters.AddWithValue("@agentType", entity.agentType); command.Parameters.AddWithValue("@subject", entity.subject); command.Parameters.AddWithValue("@content", entity.content); command.Parameters.AddWithValue("@sender", entity.sender); command.Parameters.AddWithValue("@attachment", entity.attachment); command.Parameters.AddWithValue("@attachmentName", entity.attachmentName); command.Parameters.AddWithValue("@creatTime", entity.creatTime); command.Parameters.AddWithValue("@type", entity.type); command.Parameters.AddWithValue("@validateStartTime", entity.validateStartTime); command.Parameters.AddWithValue("@validateEndTime", entity.validateEndTime); command.Parameters.AddWithValue("@isValidate", entity.isValidate); command.Parameters.AddWithValue("@isDelete", entity.isDelete); command.Parameters.AddWithValue("@deleteTime", entity.deleteTime); command.Parameters.AddWithValue("@toAll", entity.toAll); int i = command.ExecuteNonQuery(); mycn.Close(); mycn.Dispose(); return i; } }
/// <summary> /// Checks when a client's characters were last cached, against a timestamp received from the client. /// If the client's timestamp doesn't match the one in the DB (meaning it was older or newer), information /// about all the characters is sent to the client. /// </summary> /// <param name="Timestamp">The timestamp received from the client.</param> public static void CheckCharacterTimestamp(string AccountName, LoginClient Client, DateTime Timestamp) { MySqlCommand Command = new MySqlCommand("SELECT AccountName, NumCharacters, Character1, Character2, Character3 " + "FROM Accounts"); Command.Connection = m_Connection; EndCheckCharacterID(Command.BeginExecuteReader(System.Data.CommandBehavior.Default)); }
private static MySqlDataAdapter AdaptadorABM(MySqlConnection SqlConnection1) { MySqlCommand SqlInsertCommand1; MySqlCommand SqlUpdateCommand1; MySqlCommand SqlDeleteCommand1; MySqlDataAdapter SqlDataAdapter1 = new MySqlDataAdapter(); SqlInsertCommand1 = new MySqlCommand("AlicuotasIva_Insertar", SqlConnection1); SqlUpdateCommand1 = new MySqlCommand("AlicuotasIva_Actualizar", SqlConnection1); SqlDeleteCommand1 = new MySqlCommand("AlicuotasIva_Borrar", SqlConnection1); SqlDataAdapter1.DeleteCommand = SqlDeleteCommand1; SqlDataAdapter1.InsertCommand = SqlInsertCommand1; SqlDataAdapter1.UpdateCommand = SqlUpdateCommand1; // IMPLEMENTACIÓN DE LA ORDEN INSERT SqlInsertCommand1.Parameters.Add("p_id", MySqlDbType.Int16, 2, "IdAlicuotaALI"); SqlInsertCommand1.Parameters.Add("p_porcentaje", MySqlDbType.Decimal, 12, "PorcentajeALI"); SqlInsertCommand1.CommandType = CommandType.StoredProcedure; SqlUpdateCommand1.Parameters.Add("p_id", MySqlDbType.Int16, 2, "IdAlicuotaALI"); SqlUpdateCommand1.Parameters.Add("p_porcentaje", MySqlDbType.Decimal, 12, "PorcentajeALI"); SqlUpdateCommand1.CommandType = CommandType.StoredProcedure; // IMPLEMENTACIÓN DE LA ORDEN DELETE SqlDeleteCommand1.Parameters.Add("p_id", MySqlDbType.Int32, 2, "IdAlicuotaALI"); SqlDeleteCommand1.CommandType = CommandType.StoredProcedure; return SqlDataAdapter1; }
private void fillgridDef() { id = -1; buttonDel.Visible = false; buttonEdit.Visible = false; buttonIns.Visible = false; buttonCancel.Visible = false; DBConnect NewcConnection = new DBConnect(); NewcConnection.dbConnection(); MySqlCommand querysql = new MySqlCommand("Select * From deficiencias", DBConnect.db); try { MySqlDataAdapter dados = new MySqlDataAdapter(); dados.SelectCommand = querysql; DataTable tabela = new DataTable(); dados.Fill(tabela); BindingSource fonte = new BindingSource(); fonte.DataSource = tabela; dataGridView1.DataSource = fonte; this.dataGridView1.Columns[0].Visible = false; dataGridView1.Columns[1].HeaderText = "Deficiencia"; dados.Update(tabela); dataGridView1.AutoResizeColumns(); dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; } catch (Exception ex) { MessageBox.Show(ex.Message); } DBConnect.db.Close(); textBoxDef.Clear(); }
public bool actionCreate(Task task) { var conn = new MySqlConnection(TaskDAO.StringConnection); try { conn.Open(); var sql = "INSERT INTO tasks (title, description, created_at, user_id) VALUES (@title, @description, @created_at, @user_id)"; var cmd = new MySqlCommand(sql, conn); cmd.Parameters.AddWithValue("@title", task.Title); cmd.Parameters.AddWithValue("@description", task.Description); cmd.Parameters.AddWithValue("@created_at", DateTime.Now); cmd.Parameters.AddWithValue("@user_id", task.User.Id); cmd.ExecuteNonQuery(); return true; } catch(Exception ex) { Console.WriteLine(ex.Message); return false; } finally { conn.Close(); } }
private static void LoadCharacters() { Utilities.ConsoleStyle.Infos("Loading @characters@ .."); var query = new MySqlCommand("SELECT * FROM characters", DatabaseManager.Connection); var reader = query.ExecuteReader(); while (reader.Read()) { var character = new Models.Character() { ID = reader.GetInt32("id"), Account = reader.GetInt32("account"), Nickname = reader.GetString("nickname"), Level = reader.GetInt32("level"), Experience = reader.GetInt64("experience"), Sex = reader.GetInt32("sex"), Breed = reader.GetInt32("breed"), SkinColor = reader.GetInt32("skincolor"), HairColor = reader.GetInt32("haircolor"), PupilColor = reader.GetInt32("pupilcolor"), SkinColorFactor = reader.GetInt32("skincolorfactor"), HairColorFactor = reader.GetInt32("haircolorfactor"), Cloth = reader.GetInt32("cloth"), Face = reader.GetInt32("face"), Title = reader.GetInt32("title"), }; Characters.Add(character); } reader.Close(); Utilities.ConsoleStyle.Infos("Loaded @'" + Characters.Count + "'@ characters !"); }
private void WypelnijGridView() { txtDruzyna.Text = ""; txtImie.Text = ""; txtNazwisko.Text = ""; txtData.Text = ""; txtPozycja.Text = ""; txtWaga.Text = ""; txtWzrost.Text = ""; txtNumer.Text = ""; string constr = ConfigurationManager.ConnectionStrings["pol"].ConnectionString; using (MySqlConnection con = new MySqlConnection(constr)) { using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM pilkarze")) { using (MySqlDataAdapter sda = new MySqlDataAdapter()) { cmd.Connection = con; sda.SelectCommand = cmd; using (DataTable dt = new DataTable()) { sda.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind(); } } } } }
internal static DataTable ExecuteTable(string sql, string connStr) { MySqlCommand cmd = new MySqlCommand(); MySqlDataAdapter adapter = new MySqlDataAdapter(); adapter.SelectCommand = cmd; DataTable dt = new DataTable(); try { MySqlConnection conn = GetConnection(connStr); cmd.Connection = conn; cmd.CommandText = sql; cmd.CommandType = CommandType.Text; cmd.CommandTimeout = 240; adapter.Fill(dt); adapter.Dispose(); cmd.Dispose(); conn.Close(); } catch (Exception ex) { dt = new DataTable(); } return dt; }
protected void Dodaj(object sender, EventArgs e) { string DruzynaID = txtDruzyna.Text; string Imie = txtImie.Text; string Nazwisko = txtNazwisko.Text; string Data = txtData.Text; string Pozycja = txtPozycja.Text; string Waga = txtWaga.Text; string Wzrost = txtWzrost.Text; string Numer = txtNumer.Text; string sDate = String.Format("{0:yyyy-mm-dd}", Data); MySqlConnection polaczenie = new MySqlConnection(url); MySqlCommand cmd = new MySqlCommand("INSERT INTO pilkarze (ID_Druzyny, Imie, Nazwisko, Data_urodz, Pozycja, Waga, Wzrost, Nr_Kosz) VALUES (@IdDruzyny, @imie, @nazwisko, @data, @pozycja, @waga, @wzrost, @numer)", polaczenie); MySqlDataAdapter sda = new MySqlDataAdapter(); cmd.Parameters.AddWithValue("@IdDruzyny", DruzynaID); cmd.Parameters.AddWithValue("@imie", Imie); cmd.Parameters.AddWithValue("@nazwisko", Nazwisko); cmd.Parameters.AddWithValue("@data", sDate); cmd.Parameters.AddWithValue("@pozycja", Pozycja); cmd.Parameters.AddWithValue("@waga", Waga); cmd.Parameters.AddWithValue("@wzrost", Wzrost); cmd.Parameters.AddWithValue("@numer", Numer); polaczenie.Open(); cmd.ExecuteNonQuery(); polaczenie.Close(); this.WypelnijGridView(); }
/// <summary> /// Initializes a new instance of the <see cref="ManagerGeneralItemStagesGui"/> class. /// </summary> /// <param name="itemid">The itemid.</param> public ManagerGeneralItemStagesGui(string itemid) { //Login.close = 1; InitializeComponent(); this.WindowStartupLocation = WindowStartupLocation.CenterScreen; this.itemID = itemid; try { MySqlConnection MySqlConn = new MySqlConnection(Login.Connectionstring); MySqlConn.Open(); string Query1 = "select itemName from item where itemid='" + itemID + "'"; MySqlCommand MSQLcrcommand1 = new MySqlCommand(Query1, MySqlConn); MSQLcrcommand1.ExecuteNonQuery(); MySqlDataAdapter mysqlDAdp = new MySqlDataAdapter(MSQLcrcommand1); MySqlDataReader dr = MSQLcrcommand1.ExecuteReader(); while (dr.Read()) { if (!dr.IsDBNull(0)) { itemName = dr.GetString(0); } } MySqlConn.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } type_comboBox.Items.Add("רישום"); type_comboBox.Items.Add("בעבודה"); type_comboBox.Items.Add("תיקון"); type_comboBox.Items.Add("פסול"); type_comboBox.Items.Add("גמר ייצור"); type_comboBox.Items.Add("הסתיים"); type_comboBox.SelectedIndex = 0; itemidlabel.Content = itemID; itemnamelabel.Content = itemName; try { MySqlConnection MySqlConn = new MySqlConnection(Login.Connectionstring); MySqlConn.Open(); string Query1 = ("SELECT itemStageOrder as `מספר שלב`,stageName as `שם שלב` ,stage_discription as `תאור השלב` FROM item WHERE itemid='" + itemID + "' and itemStatus='רישום' "); MySqlCommand MSQLcrcommand1 = new MySqlCommand(Query1, MySqlConn); MSQLcrcommand1.ExecuteNonQuery(); MySqlDataAdapter mysqlDAdp = new MySqlDataAdapter(MSQLcrcommand1); dt.Clear(); mysqlDAdp.Fill(dt); dataGrid1.ItemsSource = dt.DefaultView; mysqlDAdp.Update(dt); MySqlConn.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void buttonCadastrar_Click(object sender, EventArgs e) { MySqlConnection conn = null; try { conn = Conexao.getConexao(); MySqlCommand cmd = new MySqlCommand("call cadastra_pizza(@nome, @tamanho, @preco)", conn); cmd.Prepare(); cmd.Parameters.AddWithValue("@nome", this.txt_nome.Text); cmd.Parameters.AddWithValue("@tamanho", this.cmb_tamanho.Text); cmd.Parameters.AddWithValue("@preco", this.txt_preco.Text); MySqlDataReader rs = cmd.ExecuteReader(); rs.Read(); if (!rs.HasRows) { conn.Close(); new SuccessDialog("Pizza cadastrada com sucesso!"); this.Close(); } else { String error = rs.GetString(0); conn.Close(); new ErrorDialog(error); } } catch (Exception err) { if (conn != null) conn.Close(); new ErrorDialog(err.Message); } }
public static DataTable showAllStudent(out string error) { try { using (MySqlConnection connection = new ConnectionManager().GetDatabaseConnection()) { using (MySqlCommand command = new MySqlCommand("sp_ShowAllStudent", connection)) { command.CommandType = CommandType.StoredProcedure; MySqlDataAdapter adapter = new MySqlDataAdapter(); DataSet dSet = new DataSet(); connection.Open(); adapter.SelectCommand = command; adapter.Fill(dSet); connection.Close(); DataTable dt = dSet.Tables[0]; error = null; return dt; } } } catch (Exception ex) { error = ex.Message; return null; } }
public static void AddCharacter(Models.Character character) { var query = new MySqlCommand("INSERT INTO characters (id, account, nickname, level, experience, sex, breed, skincolor," + " haircolor, pupilcolor, skincolorfactor, haircolorfactor, cloth, face, title) VALUES " + "(@id, @account, @nickname, @level, @experience, @sex, @breed, @skincolor, @haircolor," + " @pupilcolor, @skincolorfactor, @haircolorfactor, @cloth, @face, @title)", DatabaseManager.Connection); query.Parameters.Add(new MySqlParameter("@id", character.ID)); query.Parameters.Add(new MySqlParameter("@account", character.Account)); query.Parameters.Add(new MySqlParameter("@nickname", character.Nickname)); query.Parameters.Add(new MySqlParameter("@level", character.Level)); query.Parameters.Add(new MySqlParameter("@experience", character.Experience)); query.Parameters.Add(new MySqlParameter("@sex", character.Sex)); query.Parameters.Add(new MySqlParameter("@breed", character.Breed)); query.Parameters.Add(new MySqlParameter("@skincolor", character.SkinColor)); query.Parameters.Add(new MySqlParameter("@haircolor", character.HairColor)); query.Parameters.Add(new MySqlParameter("@pupilcolor", character.PupilColor)); query.Parameters.Add(new MySqlParameter("@skincolorfactor", character.SkinColorFactor)); query.Parameters.Add(new MySqlParameter("@haircolorfactor", character.HairColorFactor)); query.Parameters.Add(new MySqlParameter("@cloth", character.Cloth)); query.Parameters.Add(new MySqlParameter("@face", character.Face)); query.Parameters.Add(new MySqlParameter("@title", character.Title)); query.ExecuteNonQuery(); Characters.Add(character); }
protected void ExmSpecificReq(object sender, EventArgs e) { string Date = this.exm_sp_req_date.Value; string Time = this.exm_sp_req_time.Value; string Exam_Type = this.exm_sp_req_exmtype.Value; string Room_no = this.exm_sp_req_rno.Value; string Year_1 = this.exm_sp_req_yr1.Value; string Department_1 = this.exm_sp_req_dept1.Value; string QP_1 = this.exm_sp_req_ttlqp1.Value; string OR_1 = this.exm_sp_req_othreq1.Value; string OR_1_NO = this.exm_sp_req_otrnos1.Value; string Year_2 = this.exm_sp_req_yr2.Value; string Department_2 = this.exm_sp_req_dept2.Value; string QP_2 = this.exm_sp_req_ttlqp2.Value; string OR_2 = this.exm_sp_req_othreq2.Value; string OR_2_NO = this.exm_sp_req_othnos2.Value; MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connection); string queryStr; MySql.Data.MySqlClient.MySqlCommand cmd; conn.Open(); try { queryStr = "INSERT INTO student.requirements (Date, Time, Room_no, Exam_Type, Year_1, Department_1, QP_1, OR_1, OR_1_NO, Year_2, Department_2, QP_2, OR_2, OR_2_NO) VALUES (@Date, @Time, @Room_no, @Exam_Type, @Year_1, @Department_1, @QP_1, @OR_1, @OR_1_NO, @Year_2, @Department_2, @QP_2, @OR_2, @OR_2_NO);"; cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn); cmd.Parameters.AddWithValue("Date", @Date); cmd.Parameters.AddWithValue("Time", @Time); cmd.Parameters.AddWithValue("Room_no", @Room_no); cmd.Parameters.AddWithValue("Exam_Type", @Exam_Type); cmd.Parameters.AddWithValue("Year_1", @Year_1); cmd.Parameters.AddWithValue("Department_1", @Department_1); cmd.Parameters.AddWithValue("QP_1", @QP_1); cmd.Parameters.AddWithValue("OR_1", @OR_1); cmd.Parameters.AddWithValue("OR_1_NO", @OR_1_NO); cmd.Parameters.AddWithValue("Year_2", @Year_2); cmd.Parameters.AddWithValue("Department_2", @Department_2); cmd.Parameters.AddWithValue("QP_2", @QP_2); cmd.Parameters.AddWithValue("OR_2", @OR_2); cmd.Parameters.AddWithValue("OR_2_NO", @OR_2_NO); cmd.ExecuteNonQuery(); conn.Close(); } catch (Exception) { } finally { if (conn.State == System.Data.ConnectionState.Open) { conn.Close(); } } }
protected void InsertEntity <T>(T entity) { List <T> result = new List <T>(); Type entityType = typeof(T); T instance = (T)Activator.CreateInstance(entityType); List <PropertyInfo> columns = instance.GetType().GetProperties().ToList(); MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(); cmd.Connection = connection; try { connection.Open(); StringBuilder columnsForInsert = new StringBuilder(); StringBuilder parametersForInsert = new StringBuilder(); foreach (PropertyInfo prop in columns) { columnsForInsert.AppendFormat("`{0}` ,", prop.Name); if (Attribute.IsDefined(prop, typeof(ID))) { parametersForInsert.AppendFormat("NULL ,", prop.Name); } else { parametersForInsert.AppendFormat("@{0},", prop.Name); cmd.Parameters.AddWithValue(String.Format("@{0}", prop.Name), prop.GetValue(entity, null)); } } string columnsInsert = columnsForInsert.ToString(); columnsInsert = RemoveLastComma(columnsInsert); string parametersInsert = parametersForInsert.ToString(); parametersInsert = RemoveLastComma(parametersInsert); string sqlCommand = String.Format("insert into `{0}` ({1}) values({2})" , entityType.Name , columnsInsert , parametersInsert); cmd.CommandText = sqlCommand; cmd.ExecuteNonQuery(); } catch { throw; } finally { connection.Close(); } }
public static MySqlResponse querySQL(string stm) { String cs = @"server=" + IP + ";port=3306;userid=bear;password=%Pb?fYW@ydP9RLqeTnfSW-u!23c$f=%#;database=mud"; var con = new MySqlConnection(cs); con.Open(); Console.WriteLine(stm); var cmd = new MySql.Data.MySqlClient.MySqlCommand(stm, con); MySqlDataReader rdr = cmd.ExecuteReader(); return(new MySqlResponse(rdr, con)); }
public List<TournamentMatchModel> GetTournamentMatchList() { oMySQLData.MySqlConnection oCon = new oMySQLData.MySqlConnection("Server=localhost;Database=betting;Uid=root;Pwd=Mysqlm@rch101984;"); oCon.Open(); string fetchQuery = "SELECT * FROM tbltournaments WHERE fldisactive = 1 ORDER BY fldTournamentDate DESC"; List<TournamentMatchModel> tournamentmatches = new List<TournamentMatchModel>(); oMySQLData.MySqlCommand cmd = new oMySQLData.MySqlCommand(fetchQuery, oCon); cmd.ExecuteNonQuery(); oMySQLData.MySqlDataReader reader = cmd.ExecuteReader(); string matchQuery; while (reader.Read()) { TournamentMatchModel tournamentmatch = new TournamentMatchModel(); tournamentmatch.TournamentID = Convert.ToInt32(reader["fldtournamentid"]); tournamentmatch.TournamentName = (reader["fldTournamentName"]).ToString(); oMySQLData.MySqlConnection oConmatches = new oMySQLData.MySqlConnection("Server=localhost;Database=betting;Uid=root;Pwd=Mysqlm@rch101984;"); oConmatches.Open(); matchQuery = "SELECT * FROM view_matchlistdetails WHERE TournamentID = " + tournamentmatch.TournamentID + " ORDER BY fldmatchdate DESC LIMIT 3"; oMySQLData.MySqlCommand cmdmatches = new oMySQLData.MySqlCommand(matchQuery, oConmatches); cmdmatches.ExecuteNonQuery(); oMySQLData.MySqlDataReader matchreader = cmdmatches.ExecuteReader(); List<MatchModel> matches = new List<MatchModel>(); while (matchreader.Read()) { MatchModel match = new MatchModel(); match.TeamOne = matchreader["TeamOne"].ToString(); match.TeamTwo = matchreader["TeamTwo"].ToString(); match.MatchDate = Convert.ToDateTime(matchreader["fldMatchDate"]); matches.Add(match); } tournamentmatch.Matches = matches; matchreader.Close(); tournamentmatches.Add(tournamentmatch); } oCon.Close(); return tournamentmatches; }
public void Fun_ExtraerAñoMinimo() { sql = string.Format("select AnioIngreso from matricula order by AnioIngreso limit 1;"); cnx.Open(); cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, cnx); MySql.Data.MySqlClient.MySqlDataReader Reg = cmd.ExecuteReader(); if (Reg.Read()) { Var_anio_primario = (int)Convert.ToDouble(Reg["AnioIngreso"].ToString()); } cnx.Close(); }
public void Fun_ExtraerAñoMaximo() { sql = string.Format("select max(year(FechaIngreso)) as 'Anio' from matricula;"); cnx.Open(); cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, cnx); MySql.Data.MySqlClient.MySqlDataReader Reg = cmd.ExecuteReader(); if (Reg.Read()) { Var_anio_final = (int)Convert.ToDouble(Reg["Anio"].ToString()); } cnx.Close(); }
private void Form3_Load(object sender, EventArgs e) { var a = new EquipmentUI(); MySql.Data.MySqlClient.MySqlConnection conn = new MySqlConnection(); string myConnectionString; myConnectionString = "server=127.0.0.1;" + "uid=root;" + "pwd=root;" + "SslMode=none;" + "database=tribes_system"; conn.ConnectionString = myConnectionString; conn.Open(); using (MySqlConnection con = new MySqlConnection(myConnectionString)) { using (MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand("SELECT items.id,items.name,items.stocks,category.description,items.description,items.isDeployable,items.isDamaged,items.isOnrepair,items.isRented,items.isDeployed,items.isDamagedBeyondRepair FROM items left join category on items.categoryID = category.id where items.id =" + EquipmentUI.sendtext, conn)) { cmd.CommandType = CommandType.Text; using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd)) { MySqlDataReader myreader = cmd.ExecuteReader(); if (myreader.Read()) { Label2.Text = myreader.GetValue(1).ToString(); Label4.Text = myreader.GetValue(3).ToString(); Label8.Text = myreader.GetValue(2).ToString(); if (myreader.GetValue(4).ToString() == "") { Label6.Text = "Not specified"; } else { Label6.Text = myreader.GetValue(4).ToString(); } Label13.Text = myreader.GetValue(5).ToString(); Label14.Text = myreader.GetValue(6).ToString(); Label15.Text = myreader.GetValue(7).ToString(); Label16.Text = myreader.GetValue(8).ToString(); dep.Text = myreader.GetValue(9).ToString(); dbr.Text = myreader.GetValue(10).ToString(); this.Text = myreader.GetValue(1).ToString(); } myreader.Close(); } } } conn.Close(); }
public ArrayList getTrips() { MySql.Data.MySqlClient.MySqlConnection conn; string myConnectionString = ConfigurationManager.ConnectionStrings["PhpMySqlRemoteDB"].ConnectionString; conn = new MySql.Data.MySqlClient.MySqlConnection(); try { conn.ConnectionString = myConnectionString; conn.Open(); ArrayList tripArray = new ArrayList(); MySql.Data.MySqlClient.MySqlDataReader mySQLReader = null; string sqlString = "SELECT * FROM Trips"; MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sqlString, conn); mySQLReader = cmd.ExecuteReader(); while (mySQLReader.Read()) { Trip t = new Trip(); t.TripID = mySQLReader.GetInt32(0); t.Username = mySQLReader.GetString(1); t.From_City_Country = mySQLReader.GetString(2); t.To_City_Country = mySQLReader.GetString(3); t.TransportationType = mySQLReader.GetString(4); t.OutboundTripDetails_Day = mySQLReader.GetDateTime(5); t.OutboundTripDetails_Time = mySQLReader.GetTimeSpan(6); t.OutboundTripDetails_Duration = mySQLReader.GetFloat(7); t.AddAReturnTrip = mySQLReader.GetBoolean(8); t.ReturnTripDetails_Day = mySQLReader.GetDateTime(9); t.ReturnTripDetails_Time = mySQLReader.GetTimeSpan(10); t.ReturnTripDetails_Duration = mySQLReader.GetFloat(11); t.AvailableWeight = mySQLReader.GetFloat(12); t.ExcludedCategories = mySQLReader.GetString(13); t.TripNote = mySQLReader.GetString(14); tripArray.Add(t); } return(tripArray); } catch (MySql.Data.MySqlClient.MySqlException ex) { throw ex; } finally { conn.Close(); } }
protected void btnDelete_Click(object sender, EventArgs e) { foreach (GridViewRow row in GridView1.Rows) { CheckBox checkbox = (CheckBox)row.FindControl("cbSelect"); TextBox txtgvBookCode = (TextBox)row.FindControl("txtgvBookCode"); TextBox txtgvBookName = (TextBox)row.FindControl("txtgvBookName"); TextBox txtgvBookAvailability = (TextBox)row.FindControl("txtgvBookAvailability"); int i_AdminID = Convert.ToInt32(Session["AdminId"]); if (checkbox.Checked) { string i_BookCode = Convert.ToString(GridView1.DataKeys[row.RowIndex].Value); string connstring = System.Configuration.ConfigurationManager.ConnectionStrings["msuconnectionstring"].ToString(); conn = new MySql.Data.MySqlClient.MySqlConnection(connstring); conn.Open(); using (conn) { using (cmd = new MySql.Data.MySqlClient.MySqlCommand("uspBookDelete", conn)) { cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add("i_BookCode", MySql.Data.MySqlClient.MySqlDbType.VarChar).Value = Convert.ToString(txtgvBookCode.Text.Trim()); cmd.Parameters.Add("i_BookName", MySql.Data.MySqlClient.MySqlDbType.VarChar).Value = Convert.ToString(txtgvBookName.Text); cmd.Parameters.Add("i_BookAvailability", MySql.Data.MySqlClient.MySqlDbType.Int32).Value = Convert.ToInt32(txtgvBookAvailability.Text.Trim()); cmd.Parameters.Add("i_AdminID", MySql.Data.MySqlClient.MySqlDbType.Int32).Value = i_AdminID; if (cmd.ExecuteNonQuery() > 0) { string script2 = "alert(\"Rows Deleted\")"; ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script2, true); } else { string script3 = "alert(\"Error while deleting data\")"; ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script3, true); } } } conn.Close(); } } if (ddlSearchBy.SelectedValue == "Department") { BindGrid(); } if (ddlSearchBy.SelectedValue == "BookCode") { BindGridForBookCode(); } }
//new code from crackstation private void registerUserWithSlowHash() { try { string connString = System.Configuration.ConfigurationManager.ConnectionStrings["MywebConnection"].ToString(); con = new MySql.Data.MySqlClient.MySqlConnection(connString); con.Open(); querystr = ""; querystr = "INSERT INTO mydatabase.registertable(Username,DOB,Mobile,slowHashSalt)" + "VALUES(?username,?datebirth,?mob,?slowhashsalt)"; cmd = new MySqlCommand(querystr, con); cmd.Parameters.AddWithValue("?username", Username.Text); cmd.Parameters.AddWithValue("?datebirth", dob.Text); cmd.Parameters.AddWithValue("?mob", mob.Text); string saltHashReturned = PasswordStorage.CreateHash(passwd.Text); int commaIndex = saltHashReturned.IndexOf(":"); string extractedString = saltHashReturned.Substring(0, commaIndex); commaIndex = saltHashReturned.IndexOf(":"); extractedString = saltHashReturned.Substring(commaIndex + 1); commaIndex = extractedString.IndexOf(":"); string salt = extractedString.Substring(0, commaIndex); commaIndex = extractedString.IndexOf(":"); extractedString = extractedString.Substring(commaIndex + 1); string hash = extractedString; //from the first : to the second : is the salt //from the second : to the end is the hash cmd.Parameters.AddWithValue("?slowhashsalt", saltHashReturned); cmd.ExecuteReader(); con.Close(); //ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('You have been Succesfully Registered! Click O.K to navigate to Homepage.');window.location.replace('Default.aspx');</script>"); cmd.Dispose(); clearfields(); ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript' >alertMX('Registered Succesfully! Click OK');</script>"); //ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript' >myalert('Test', 'This is a test modal dialog');</script>"); } catch (MySqlException reg) { Console.WriteLine("{0}+MySql Exceptions", reg); } finally { if (!(con == null)) { con.Dispose(); } } }
private void submitRadio() { String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString(); conn = new MySql.Data.MySqlClient.MySqlConnection(connString); conn.Open(); queryStr = ""; queryStr = "SELECT StudentName FROM selfevascore WHERE StudentName ='" + svr.Text + "' "; cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn); reader = cmd.ExecuteReader(); if (reader.HasRows) { reader.Read(); check = reader.GetString(reader.GetOrdinal("StudentName")); } reader.Close(); conn.Close(); if (check == svr.Text) { conn = new MySql.Data.MySqlClient.MySqlConnection(connString); conn.Open(); queryStr = ""; queryStr = "UPDATE selfevascore SET 3c ='" + RadioButtonList1.Text + "'+'" + RadioButtonList2.Text + "'+'" + RadioButtonList3.Text + "'+'" + RadioButtonList4.Text + "'+'" + RadioButtonList5.Text + "'+'" + RadioButtonList6.Text + "'+'" + RadioButtonList7.Text + "'+'" + RadioButtonList8.Text + "'+'" + RadioButtonList9.Text + "'+'" + RadioButtonList10.Text + "'WHERE StudentName = '" + svr.Text + "' "; Labelcheck.Text = "Changes Have been Submitted Successfully"; Labelcheck.ForeColor = System.Drawing.Color.Green; } else { conn = new MySql.Data.MySqlClient.MySqlConnection(connString); conn.Open(); queryStr = ""; queryStr = "INSERT INTO selfevascore ( StudentName, 3c)" + "VALUES('" + svr.Text + "','" + RadioButtonList1.Text + "'+'" + RadioButtonList2.Text + "'+'" + RadioButtonList3.Text + "'+'" + RadioButtonList4.Text + "'+'" + RadioButtonList5.Text + "'+'" + RadioButtonList6.Text + "'+'" + RadioButtonList7.Text + "'+'" + RadioButtonList8.Text + "'+'" + RadioButtonList9.Text + "'+'" + RadioButtonList10.Text + "')"; Labelcheck.Text = "Submitted Successfully"; Labelcheck.ForeColor = System.Drawing.Color.Green; } cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn); cmd.ExecuteReader(); conn.Close(); }
protected void btnFacultyInsert_Click(object sender, EventArgs e) { reqinsFacultyCode.Enabled = true; reqinsFacultyFirstName.Enabled = true; reqinsFacultyLastName.Enabled = true; reqinsQualification.Enabled = true; reqinsDesignation.Enabled = true; string connstring = System.Configuration.ConfigurationManager.ConnectionStrings["msuconnectionstring"].ToString(); conn = new MySql.Data.MySqlClient.MySqlConnection(connstring); conn.Open(); using (conn) { using (cmd = new MySql.Data.MySqlClient.MySqlCommand("uspFacultyInsert", conn)) { cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add("i_FacultyCode", MySql.Data.MySqlClient.MySqlDbType.VarChar).Value = txtinsFacultyCode.Text.Trim(); cmd.Parameters.Add("i_FacultyFirstName", MySql.Data.MySqlClient.MySqlDbType.VarChar).Value = txtinsFacultyFirstName.Text; cmd.Parameters.Add("i_FacultyLastName", MySql.Data.MySqlClient.MySqlDbType.VarChar).Value = txtinsFacultyLastName.Text; cmd.Parameters.Add("i_Qualification", MySql.Data.MySqlClient.MySqlDbType.VarChar).Value = txtinsQualification.Text; cmd.Parameters.Add("i_Designation", MySql.Data.MySqlClient.MySqlDbType.VarChar).Value = txtinsDesignation.Text; cmd.Parameters.Add("o_FacultyID", MySql.Data.MySqlClient.MySqlDbType.Int32); cmd.Parameters["o_FacultyID"].Direction = ParameterDirection.Output; cmd.Parameters.Add("o_isSameFacultyCodeExists", MySql.Data.MySqlClient.MySqlDbType.Int32); cmd.Parameters["o_isSameFacultyCodeExists"].Direction = ParameterDirection.Output; if (cmd.ExecuteNonQuery() > 0) { if (Convert.ToInt32(cmd.Parameters["o_isSameFacultyCodeExists"].Value) == 0) { string script3 = "alert(\"The Faculty is Saved\")"; ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script3, true); } } else if (Convert.ToInt32(cmd.Parameters["o_isSameFacultyCodeExists"].Value) == 1) { string script4 = "alert(\"This Faculty Code already Exists. Please enter any other Faculty Code\")"; ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script4, true); } else { string script5 = "alert(\"Error in saving the data\")"; ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script5, true); } } } conn.Close(); BindFacultyGrid(); }
//private static MySqlConnection conn; static public DataSet Query(string constr, string sql) { MySqlConnection conn = new MySqlConnection(constr); conn.Open(); DataSet reds = new DataSet(); MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn); //cmd.ExecuteReader MySql.Data.MySqlClient.MySqlDataAdapter da = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd); da.Fill(reds); return(reds); }
public MySqlCommand ToSqlCommand(MySqlConnection dbConnect) { var cmd = new MySql.Data.MySqlClient.MySqlCommand(SqlCode, dbConnect); if (SqlParameters != null) { foreach (var i in SqlParameters) { cmd.Parameters.Add(i); } } return(cmd); }
/// <summary> /// 执行命令 /// </summary> /// <param name="conn">Connection对象</param> /// <param name="cmdType">命令类型(存储过程或SQL语句)</param> /// <param name="cmdText">SQL语句或存储过程名</param> /// <param name="cmdParms">MySql.Data.MySqlClient.MySqlCommand参数数组</param> /// <returns>返回受引响的记录行数</returns> public static int ExecuteNonQuery(MySqlConnection conn, CommandType cmdType, string cmdText, params MySql.Data.MySqlClient.MySqlParameter[] cmdParms) { MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(); cmd.CommandTimeout = 600; PrepareCommand(conn, null, cmd, cmdType, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return(val); }
public void clearAllSections() { MySql.Data.MySqlClient.MySqlCommand cmd1; MySql.Data.MySqlClient.MySqlCommand cmd2; cmd1 = new MySql.Data.MySqlClient.MySqlCommand("clearAllSchedules", cnn); cmd1.CommandType = CommandType.StoredProcedure; cmd1.ExecuteNonQuery(); cmd2 = new MySql.Data.MySqlClient.MySqlCommand("clearAllSections", cnn); cmd2.CommandType = CommandType.StoredProcedure; cmd2.ExecuteNonQuery(); }
protected void btnSubjectInsert_Click(object sender, EventArgs e) { reqinsSubjectCode.Enabled = true; reqinsCourseCode.Enabled = true; reqinsDepartmentCode.Enabled = true; reqinsSubjectName.Enabled = true; string connstring = System.Configuration.ConfigurationManager.ConnectionStrings["msuconnectionstring"].ToString(); conn = new MySql.Data.MySqlClient.MySqlConnection(connstring); conn.Open(); using (conn) { using (cmd = new MySql.Data.MySqlClient.MySqlCommand("uspSubjectInsert", conn)) { cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add("i_SubjectCode", MySql.Data.MySqlClient.MySqlDbType.VarChar).Value = txtinsSubjectCode.Text.Trim(); cmd.Parameters.Add("i_DepartmentCode", MySql.Data.MySqlClient.MySqlDbType.VarChar).Value = txtinsDepartmentCode.Text.Trim(); cmd.Parameters.Add("i_CourseCode", MySql.Data.MySqlClient.MySqlDbType.VarChar).Value = txtinsCourseCode.Text; cmd.Parameters.Add("i_SubjectName", MySql.Data.MySqlClient.MySqlDbType.VarChar).Value = txtinsSubjectName.Text.Trim(); cmd.Parameters.Add("i_AdminID", MySql.Data.MySqlClient.MySqlDbType.VarChar).Value = Convert.ToInt32(Session["AdminId"]); cmd.Parameters.Add("o_SubjectID", MySql.Data.MySqlClient.MySqlDbType.Int32); cmd.Parameters["o_SubjectID"].Direction = ParameterDirection.Output; cmd.Parameters.Add("o_isSameSubjectCodeExists", MySql.Data.MySqlClient.MySqlDbType.Int32); cmd.Parameters["o_isSameSubjectCodeExists"].Direction = ParameterDirection.Output; if (cmd.ExecuteNonQuery() > 0) { if (Convert.ToInt32(cmd.Parameters["o_isSameSubjectCodeExists"].Value) == 0) { string script = "alert(\"The Course is Saved\")"; ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true); } } else if (Convert.ToInt32(cmd.Parameters["o_isSameSubjectCodeExists"].Value) == 1) { string script1 = "alert(\"This Course Code already Exists. Please enter other Course Code\")"; ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script1, true); } else { string script2 = "alert(\"Error in saving the data\")"; ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script2, true); } } } conn.Close(); BindSubjectGrid(); }
public void createTable() { frmCreate frmCreateDataBase = new frmCreate(); frmCreateDataBase.Text = "Create table"; frmCreateDataBase.lblNombre.Text = "Table name:"; frmCreateDataBase.ShowDialog(); if (frmCreateDataBase.DialogResult == DialogResult.OK) { string tableName = frmCreateDataBase.txtNombreDatabase.Text; string query = "CREATE TABLE " + tableName + "("; bool addedFirstField = false; frmFields frmFields = new frmFields(); frmFields.ShowDialog(); if (frmFields.DialogResult == DialogResult.OK) { int size = frmFields.fields.Count; int count = 1; foreach (string item in frmFields.fields) { if (count == size) { query += item + " )"; } else { query += item + ","; } count += 1; } try { query = query + ";"; if (ConfirmQuery(query) == true) { mySqlCommand = new MySqlCommand(query, mySqlConnection); mySqlCommand.ExecuteNonQuery(); PutDataInTreeView(); ShowLog("Query: " + query); } } catch (Exception e) { DialogResult dialog = MessageBox.Show("ERROR to extract data: " + e.ToString(), "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
/// <summary> /// Runs a sql query /// </summary> /// <param name="queryString">Command to be run on mysql</param> /// <param name="delimiter">Used to delimit the columns of the output from a select query</param> /// <returns></returns> public string RunCommand(string queryString, string delimiter) { // output string string output = ""; int debug = 0; string lastSuccessful = ""; try { // check if conn has been created, and create it if not if (conn == null) { ConnectToDB(); } // open connection OpenConnection(); // run the query MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(queryString, conn); // create streamreader to read the data from output MySql.Data.MySqlClient.MySqlDataReader dr = cmd.ExecuteReader(); // read the file - columns are delimited by the selected delimiter while (dr.Read()) { debug++; lastSuccessful = ""; for (int x = 0; x < dr.FieldCount; x++) { lastSuccessful += dr[x].ToString() + delimiter; output += dr[x].ToString(); output += delimiter; } output += System.Environment.NewLine; } } catch (Exception ex) { // error was encountered throw new Exception("Error while trying to run query. Error Message: \"" + ex.Message + "\" at row " + debug + " with: " + lastSuccessful); } finally { // close connection CloseConnection(); } return(output); }
/*! * \brief This handler handles when the user clicks the "Connect Data" button. * \details This handler connects to the contract marketplace via the "CntrtMrktplc" connection string, and queries all of the available contracts. * \param sender <b>object</b> * \param e <b>RoutedEventArgs</b> */ private void connectDataBTN_Click(object sender, RoutedEventArgs e) { // Connect to database string conStr = ConfigurationManager.ConnectionStrings["CntrtMrktplc"].ConnectionString; StringBuilder cmdSB = new StringBuilder("SELECT Client_Name, Job_Type, Quantity, Origin, Destination, Van_Type FROM Contract;"); MySqlDataReader reader = null; using (MySqlConnection connection = new MySqlConnection(conStr)) { MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(cmdSB.ToString(), connection); try { connection.Open(); File.AppendAllText(@"Log\Log.log", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.ff") + ": Buyer connected to the contract marketplace database.\n"); databaseConnected = true; // bool that handles localUser.setOrderProgress(true); reader = cmd.ExecuteReader(); // Once connected, fill textbox with information while (reader.Read()) { databaseView.Items.Add(new contractParams { clientName = reader["Client_Name"].ToString(), jobType = int.Parse(reader["Job_Type"].ToString()), quantity = int.Parse(reader["Quantity"].ToString()), origin = reader["Origin"].ToString(), destination = reader["Destination"].ToString(), vanType = int.Parse(reader["Van_Type"].ToString()) }); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { connection.Close(); } } // Once bool is changed, display database in listview box //tommy if (databaseConnected == true) { connectDataBTN.IsEnabled = false; orderStatusLabel.Content = "Select a Contract"; // display database // Add items from database to Contract list } }
public string RefundPayment(int paymentid, int customer_id, int staff_id, int rental_id, decimal amount, DateTime paymentDate, string movie_title) { //string conn = "server=localhost; userid=root;password=ecetera;database=sakila;"; //Use the 'client' variable to call operations on the service. string info = ""; CardConsumer cc = new CardConsumer(); //here just use a randon credti card since we are not fully simulating a bank and accounts etc string ccnumber = RandomCreditCardNumberGenerator.GenerateMasterCardNumber(); //apply credit via the bank service cc.Credit(ccnumber, double.Parse(amount.ToString())); //account this refund in sakila database payment table using (MySqlConnection connection = new MySqlConnection(GetConnection())) { MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(); cmd.Connection = connection; cmd.Parameters.AddWithValue("@customer_id", customer_id); cmd.Parameters.AddWithValue("@staff_id", staff_id); cmd.Parameters.AddWithValue("@rental_id", rental_id); cmd.Parameters.AddWithValue("@amount", amount); cmd.Parameters.AddWithValue("@payment_date", paymentDate); cmd.Parameters.AddWithValue("@lastupdate", DateTime.Now); cmd.CommandText = "INSERT INTO payment(customer_id,staff_id,rental_id,amount,payment_date,last_update) VALUES" + "(@customer_id, @staff_id, @rental_id, @amount, @payment_date, @lastupdate);"; try { connection.Open(); int result = cmd.ExecuteNonQuery(); if (result == -1) { info = "error in refunding amount"; } else { info = "success"; } } finally { connection.Close(); } } return(info); }
public void GetAllStudent(GetAllStudentFromDB getAllStudentFromDB) { Dictionary <String, StudentStruct> student = new Dictionary <String, StudentStruct>(); ///conection to DB MySql.Data.MySqlClient.MySqlConnection conn; string myConnectionString; myConnectionString = "server=localhost;uid=testuser;" + "pwd=12345;database=student;"; conn = new MySql.Data.MySqlClient.MySqlConnection(); conn.ConnectionString = myConnectionString; try { //This part belong to the way to read a data from mysql into the imageFromDB conn.Open(); MySql.Data.MySqlClient.MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT studentFullname,idNumber FROM studentlist"; MySql.Data.MySqlClient.MySqlDataReader reader = cmd.ExecuteReader(); // int count = reader.FieldCount; DataTable dtCustomers = new DataTable(); dtCustomers.Load(reader); foreach (DataRow row in dtCustomers.Rows) { StudentStruct s = new StudentStruct(); s.Name = row["studentFullname"].ToString(); s.Id = Convert.ToDouble(row["idNumber"].ToString()); s.attendance = "Not present"; student.Add(s.Name + s.Id, s); } using (System.IO.StreamWriter errorlog = new System.IO.StreamWriter(@"C:\Users\rotem\Desktop\student\Finall\Finallproject\ProcessedPhotos\ProcessedPhotos\Logs\Mysql\log2.txt", true)) { errorlog.WriteLine("Connection Succeful From Roll-Call " + " " + DateTime.Now + Environment.NewLine); } } catch (MySql.Data.MySqlClient.MySqlException ex) { //write to error to log file using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\rotem\Desktop\student\Finall\Finallproject\ProcessedPhotos\ProcessedPhotos\Logs\Mysql\log.txt", true)) { file.WriteLine(ex.Message + " From Roll-Call " + " " + DateTime.Now + Environment.NewLine); } } conn.Close(); getAllStudentFromDB(new GetAllStudentToStrucet(student)); }
public string insertRegister(string userid, string password, string IdSerialNo, string email, string phone) { MySqlCommand studentComm = new MySqlCommand("SELECT * FROM `student` where rollid=@id", conn.GetConnection()); MySqlDataAdapter Studentadapter = new MySqlDataAdapter(); studentComm.Parameters.AddWithValue("@id", userid); studentComm.Connection = conn.GetConnection(); studentComm.Connection.Open(); MySqlDataReader studentreader; studentreader = studentComm.ExecuteReader(); int count = 0; string studentName = string.Empty; string userRole = string.Empty; while (studentreader.Read()) { count = count + 1; studentName = studentreader["name"].ToString(); } if (count == 1) { conn.closeConnection(); MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(); String insertQuery = "INSERT INTO users (userid, password, IdSerialNo, email, phone) VALUES (@uid,@pa,@sid,@eml,@phn)"; command.CommandText = insertQuery; command.Connection = conn.GetConnection(); command.Connection.Open(); command.Parameters.Add("@uid", MySqlDbType.VarChar).Value = userid; command.Parameters.Add("@pa", MySqlDbType.VarChar).Value = password; command.Parameters.Add("@sid", MySqlDbType.VarChar).Value = IdSerialNo; command.Parameters.Add("@eml", MySqlDbType.VarChar).Value = email; command.Parameters.Add("@phn", MySqlDbType.VarChar).Value = phone; if (command.ExecuteNonQuery() == 1) { conn.closeConnection(); return("ok"); } else { conn.closeConnection(); return("no"); } } else { conn.closeConnection(); return("authorized"); } }
private void activateuser() { try { string connString = System.Configuration.ConfigurationManager.ConnectionStrings["MywebConnection"].ToString(); con = new MySql.Data.MySqlClient.MySqlConnection(connString); con.Open(); querystr = ""; querystr = "SELECT * FROM mydatabase.activation_table WHERE Email_id=?email AND Activation_Code=?code"; cmd = new MySqlCommand(querystr, con); cmd.Parameters.AddWithValue("?email", email.Text); cmd.Parameters.AddWithValue("?code", code.Text); reader = cmd.ExecuteReader(); name = ""; while (reader.HasRows && reader.Read()) { name = reader.GetString(reader.GetOrdinal("Activation_Code")); } if (reader.HasRows) { Session["uname"] = name; Response.BufferOutput = true; Response.Redirect("Registration.aspx", false); } else { email.Text = ""; code.Text = ""; ClientScript.RegisterStartupScript(Page.GetType(), "disablevalidation", "<script language='javascript' >disableall();</script>"); ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript' >alertMX('Invalid Email / Activation Code!');</script>"); } reader.Close(); con.Close(); } catch (MySqlException ex) { Console.WriteLine("{0} Exception caught.", ex); } finally { if (cmd != null) { cmd.Dispose(); } if (con != null) { con.Close(); } } }
//check in initiate if user already voted any posts private void checkVoted() { String accountID = (String)Session["accountID"]; //check forum post voted already String connString = System.Configuration.ConfigurationManager.ConnectionStrings["CredditConnString"].ToString(); conn = new MySql.Data.MySqlClient.MySqlConnection(connString); conn.Open(); queryStr = ""; queryStr = "SELECT * FROM forum WHERE forumId='" + forumId + "'"; cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn); reader = cmd.ExecuteReader(); String vote = ""; while (reader.HasRows && reader.Read()) { vote = reader.GetString(reader.GetOrdinal("vote")); } reader.Close(); conn.Close(); // if user already voted on this forum, hide upvote/downvote if (vote.Contains("|" + accountID + "|")) { UpvoteForumButton.Visible = false; DownvoteForumButton.Visible = false; } //check comment post voted already foreach (GridViewRow row in GridView1.Rows) { threadId = row.Cells[7].Text; conn = new MySql.Data.MySqlClient.MySqlConnection(connString); conn.Open(); queryStr = ""; queryStr = "SELECT * FROM thread WHERE threadId='" + threadId + "'"; cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn); reader = cmd.ExecuteReader(); vote = ""; while (reader.HasRows && reader.Read()) { vote = reader.GetString(reader.GetOrdinal("vote")); } reader.Close(); conn.Close(); // if user already voted on this comment, hide upvote/downvote if (vote.Contains("|" + accountID + "|")) { row.Cells[0].Text = "Already Voted"; } } }
void ClaimPurchase(BasePlayer player, string command, string[] args) { List <string> itemstoremove = new List <string>(); Item[] sakerna = player.inventory.AllItems(); double maxitems = 30; if (sakerna.Count() >= 30) { SendReply(player, "You have no space in you're inventory!"); } else { string dbConnectionString = string.Format("server={0};uid={1};pwd={2};database={3};", server, uid, password, database); string query = "SELECT * FROM players_orders"; var conn = new MySql.Data.MySqlClient.MySqlConnection(dbConnectionString); conn.Open(); var cmd = new MySql.Data.MySqlClient.MySqlCommand(query, conn); var reader = cmd.ExecuteReader(); while (reader.Read()) { var someValue = reader["steamid"]; if (someValue.ToString() == player.userID.ToString() && sakerna.Count() < 30) { int amount; int.TryParse(reader["amount"].ToString(), out amount); player.GiveItem(ItemManager.CreateByName(reader["item"].ToString(), amount, 0)); sakerna = player.inventory.AllItems(); itemstoremove.Add(reader["id"].ToString()); SendReply(player, "You claimed a item!"); } } } foreach (string s in itemstoremove) { string dbConnectionString = string.Format("server={0};uid={1};pwd={2};database={3};", server, uid, password, database); string query = "DELETE FROM players_orders WHERE id=" + s; var conn = new MySql.Data.MySqlClient.MySqlConnection(dbConnectionString); conn.Open(); var cmd = new MySql.Data.MySqlClient.MySqlCommand(query, conn); cmd.ExecuteNonQuery(); conn.Close(); } }
protected void Button1_Click(object sender, EventArgs e) { String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString(); conn = new MySql.Data.MySqlClient.MySqlConnection(connString); conn.Open(); queryStr = "INSERT INTO game.info(first_name, last_name)" + "VALUES('" + TxtBoxFirstName.Text + "' , '" + TxtBoxLastName.Text + "')"; cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn); cmd.ExecuteReader(); conn.Close(); }
protected void ActiverCompte(object sender, EventArgs e) { String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString(); conn = new MySql.Data.MySqlClient.MySqlConnection(connString); conn.Open(); queryStr = ""; queryStr = "update database.tbl_user set estActif='true' where id='" + Session["IdAmis"] + "';"; cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn); cmd.ExecuteNonQuery(); conn.Close(); Response.BufferOutput = true; Response.Redirect("~/Profil/ProfilAmis.aspx", false); }
public AvatarModel(int id, string src) { MySqlConnection Conn = new MySqlConnection("server=sql9.freemysqlhosting.net;database=sql9140372;user=sql9140372;password=WSx2C8iRZx;"); var cmd = new MySql.Data.MySqlClient.MySqlCommand(); Conn.Open(); cmd.Connection = Conn; cmd.CommandText = "UPDATE users SET avatar=@src WHERE id=" + id; cmd.Prepare(); cmd.Parameters.AddWithValue("@src", src); //MySqlDataReader rdr = cmd.ExecuteReader(); cmd.ExecuteNonQuery(); Conn.Close(); }
protected void Page_Load(object sender, EventArgs e) { //if(CheckBoxList1.Items.Count > 0) //{ // CheckBoxList1.ClearSelection.; //} Globals.conn.Open(); sValue = (string)Session["SearchValue"]; //searchData(sValue); string query = $"SELECT * FROM groupa03.product Where Name LIKE '%{sValue}%' OR RecNumber LIKE '%{sValue}%' OR ID LIKE '%{sValue}%' OR Description Like '%{sValue}%' OR Price LIKE '%{sValue}%'"; var cmd = new MySql.Data.MySqlClient.MySqlCommand(query, Globals.conn); var reader = cmd.ExecuteReader(); productList = new BindingList <Product>(); while (reader.Read()) { product = new Product(); //string tmpAdd = ""; //int tmpNum; var price = reader["price"]; // get data from the title column var name = reader["Name"]; var recNumber = reader["RecNumber"]; var description = reader["Description"]; var id = reader["ID"]; product.Price = Convert.ToDouble(price); product.Name = name.ToString(); product.RecNumber = Convert.ToInt32(recNumber); product.Description = description.ToString(); product.Id = Convert.ToInt32(id); productList.Add(product); } reader.Close(); if (!IsPostBack == true) { foreach (Product p in productList) { CheckBoxList1.Items.Add(p.ToString()); } } }
public void add_date_firstDay(string date, int line, string first, string sec, string thi, string four, string fiv, string six, string sev, string eig, string nin, string ten, string ele,string twe) { DateTime dt = Convert.ToDateTime(date); //string connect = "datasource = 127.0.0.1; port = 3306;Connection Timeout=30; Min Pool Size=20; Max Pool Size=200; username = root; password = ;"; MySqlConnection conn = new MySqlConnection(connect); MySqlCommand sda = new MySqlCommand(@"insert into shedulling.tablelayout1 values ('" + dt + "','" + line + "','" + first + "','" + sec + "','" + thi + "','" + four + "','" + fiv + "','" + six + "','" + sev + "','" + eig + "','" + nin + "','" + ten + "', '" + ele + "','"+twe+ "')", conn); MySqlDataReader reader; try { conn.Open(); reader = sda.ExecuteReader(); while (reader.Read()) { } reader.Close(); conn.Close(); conn.Dispose(); } catch (Exception e) { MessageBox.Show(e.Message); } finally { if (conn != null && conn.State == ConnectionState.Open) { conn.Close(); } } }