protected void ButtonEdit_Click(object sender, EventArgs e) { buttonActive(true, false, true); SqlConnection sqlConn = new SqlConnection(myConnStr); SqlCommand cmd = new SqlCommand("select * from DateRangeTable", sqlConn); SqlDataReader MyDataReader; try { sqlConn.Open(); MyDataReader = cmd.ExecuteReader(); MyDataReader.Read(); TextBoxDateRangeId.Text = MyDataReader["DateRangeId"].ToString(); TextBoxDateRangeStart.Text = MyDataReader["DateRangeStart"].ToString(); TextBoxDateRangeEnd.Text = MyDataReader["DateRangeEnd"].ToString(); //Response.Write("<script language='javascript'> alert('Database connection openned');</script>"); } catch (Exception er) { Response.Write("<script language='javascript'> alert('Database connection failed');</script>"); //Response.Write("<script language='javascript'> alert('Customer not found!');</script>"); } finally { //sqlConn.Close(); //Response.Write("<script language='javascript'> alert('Database connection closed');</script>"); } }
protected void DropDownListSelectStaff_SelectedIndexChanged(object sender, EventArgs e) { buttonActive(false, true, false, true, false, true); SqlConnection sqlConn = new SqlConnection(myConnStr); SqlCommand cmd = new SqlCommand("select * from StaffTable where StaffId='" + DropDownListSelectStaff.SelectedValue + "'", sqlConn); SqlDataReader MyDataReader; try { sqlConn.Open(); MyDataReader = cmd.ExecuteReader(); MyDataReader.Read(); TextBoxStaffId.Text = MyDataReader["StaffId"].ToString(); TextBoxStaffFirstName.Text = MyDataReader["StaffFName"].ToString(); TextBoxStaffLastName.Text = MyDataReader["StaffLName"].ToString(); TextBoxStaffUsername.Text = MyDataReader["StaffUsername"].ToString(); TextBoxStaffPassword.Text = MyDataReader["StaffPassword"].ToString(); TextBoxStaffEmail.Text = MyDataReader["StaffEmail"].ToString(); //Response.Write("<script language='javascript'> alert('Database connection openned');</script>"); } catch (Exception er) { Response.Write("<script language='javascript'> alert('Database connection failed');</script>"); //Response.Write("<script language='javascript'> alert('Customer not found!');</script>"); } finally { sqlConn.Close(); // Response.Write("<script language='javascript'> alert('Database connection closed');</script>"); } }
private void Window_Loaded(object sender, RoutedEventArgs e) { if (Connection.MyConnection.State == ConnectionState.Broken) { Connection.MyConnection.Open(); } if (Connection.MyConnection.State == ConnectionState.Open) { using (OdbcCommand MyCommand = new OdbcCommand("SELECT duedate,priority,reminder,minute,note FROM tms_reminders WHERE rid='" + TaskReminderCount.rid + "'", Connection.MyConnection)) { OdbcDataReader MyDataReader; MyDataReader = MyCommand.ExecuteReader(); MyDataReader.Read(); duedateLab.Content = MyDataReader.GetDateTime(0).ToString("yyyy-MM-dd hh:mm tt "); priolab.Content = MyDataReader.GetString(1); title_Lab.Content = MyDataReader.GetString(2); noofhourlab.Content = TimeDisplay(MyDataReader.GetInt32(3)); string tempcomment = MyDataReader.GetString(4); if (tempcomment.Length == 0) { commentlab.Text = "<no descrption>"; } else { commentlab.Text = MyDataReader.GetString(4); } MyDataReader.Close(); } } }
protected void DropDownListSelectHelp_SelectedIndexChanged(object sender, EventArgs e) { buttonActive(false, true, false, true, false); SqlConnection sqlConn = new SqlConnection(myConnStr); SqlCommand cmd = new SqlCommand("select * from HelpTable where HelpId='" + DropDownListSelectHelp.SelectedValue + "'", sqlConn); SqlDataReader MyDataReader; try { sqlConn.Open(); MyDataReader = cmd.ExecuteReader(); MyDataReader.Read(); TextBoxHelpId.Text = MyDataReader["HelpId"].ToString(); TextBoxHelpQuestion.Text = MyDataReader["HelpQuestion"].ToString(); TextBoxHelpAnswer.Text = MyDataReader["HelpAnswer"].ToString(); //Response.Write("<script language='javascript'> alert('Database connection openned');</script>"); } catch (Exception er) { Response.Write("<script language='javascript'> alert('Database connection failed');</script>"); //Response.Write("<script language='javascript'> alert('Customer not found!');</script>"); } finally { sqlConn.Close(); // Response.Write("<script language='javascript'> alert('Database connection closed');</script>"); } }
public IEnumerable <string> GetAllValues() { List <string> valuesList = new List <string>(); string query = "SELECT * FROM user"; //TODO: Test if mysql connection is open MySqlCommand myCommand = new MySqlCommand(query, connection); MySqlDataReader MyDataReader; try { MyDataReader = myCommand.ExecuteReader(); while (MyDataReader.Read()) { //General idea: MyDataReader at [0] string int etc... valuesList.Add(MyDataReader.GetString(0)); valuesList.Add(MyDataReader.GetString(1)); } MyDataReader.Close(); } catch (Exception ex) { Console.WriteLine("Exception reading from db : " + ex); } return(valuesList); }
private void fillList() { SqlConnection sqlConn = new SqlConnection(myConnStr); SqlCommand cmd = new SqlCommand("select * from DateRangeTable", sqlConn); SqlDataReader MyDataReader; DropDownListDateRange.Items.Clear(); try { sqlConn.Open(); MyDataReader = cmd.ExecuteReader(); while (MyDataReader.Read()) { ListItem newitem = new ListItem(); newitem.Text = "Start Date: " + MyDataReader["DateRangeStart"] + ". End Date:" + MyDataReader["DateRangeEnd"]; newitem.Value = MyDataReader["DateRangeId"].ToString(); DropDownListDateRange.Items.Add(newitem); } } catch (Exception er) { Response.Write("<script language='javascript'> alert('Database connection failed');</script>"); } finally { //sqlConn.Close(); } }
/// <summary> /// Возвращает список с данными из таблицы /// </summary> /// <param name="quary">Запрос</param> /// <param name="numberReadRow">Номера тех столбцов, с которых будут браться данные </param> /// <returns></returns> public static List <List <dynamic> > MySqlQuaryOut(string quary, params int[] numberReadRow) { List <List <dynamic> > arrData = new List <List <dynamic> >(); OpenConnect(ref mySQLConn); MySqlCommand myCommand = new MySqlCommand(quary, mySQLConn); MySqlDataReader MyDataReader; MyDataReader = myCommand.ExecuteReader(); for (int i = 0; i < numberReadRow.Length; i++) { arrData.Add(new List <dynamic>()); } while (MyDataReader.Read()) { for (int i = 0; i < numberReadRow.Length; i++) { if (!MyDataReader.IsDBNull(numberReadRow[i])) { arrData[i].Add(MyDataReader.GetString(numberReadRow[i])); } else { arrData[i].Add("null"); } } } mySQLConn.Close(); return(arrData); }
private void fillList() { SqlConnection sqlConn = new SqlConnection(myConnStr); SqlCommand cmd = new SqlCommand("select * from StaffTable", sqlConn); SqlDataReader MyDataReader; DropDownListSelectStaff.Items.Clear(); try { sqlConn.Open(); MyDataReader = cmd.ExecuteReader(); while (MyDataReader.Read()) { ListItem newitem = new ListItem(); newitem.Text = MyDataReader["StaffId"] + ", " + MyDataReader["StaffFName"] + ", " + MyDataReader["StaffLName"] + ", " + MyDataReader["StaffUsername"] + ", " + MyDataReader["StaffPassword"] + ", " + MyDataReader["StaffEmail"]; newitem.Value = MyDataReader["StaffId"].ToString(); DropDownListSelectStaff.Items.Add(newitem); } } catch (Exception er) { Response.Write("<script language='javascript'> alert('Database connection failed');</script>"); } finally { sqlConn.Close(); } }
public void Load() { Thread.CurrentThread.CurrentCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone(); Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "ddd, MMM dd, yyyy"; select_dPicker.SelectedDate = DateTime.Now; note_tBox.Text = note; time_TPicker.Value = Convert.ToDateTime(hour.Replace(".", ":")); if (Connection.MyConnection.State == ConnectionState.Broken) { Connection.MyConnection.Open(); } if (Connection.MyConnection.State == ConnectionState.Open) { using (OdbcCommand MyCommand = new OdbcCommand("SELECT `tms_projects`.`project_name`,`tms_reminders`.`project` ,`tms_category`.`category_name` ,`tms_reminders`.`category` FROM `tms_reminders` INNER JOIN `tms_projects` ON `tms_projects`.`project_id`=`tms_reminders`.`project` INNER JOIN `tms_category` ON `tms_category`.`category_id`=`tms_reminders`.`category` WHERE `tms_reminders`.`rid`='" + id + "'", Connection.MyConnection)) { OdbcDataReader MyDataReader; MyDataReader = MyCommand.ExecuteReader(); MyDataReader.Read(); proname_wTBox.Text = MyDataReader.GetString(0); proid = MyDataReader.GetInt32(1); catename_wTBox.Text = MyDataReader.GetString(2); catid = MyDataReader.GetInt32(3); MyDataReader.Close(); } } }
private List <string> getHeaders() { string connectionStr = "server=localhost;user=root;database=university_lab;CharSet=utf8;password=root;"; string query = $@"select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='forms'"; List <string> resultList = new List <string>(); MySqlConnection conn = new MySqlConnection(connectionStr); MySqlCommand myCommand = new MySqlCommand(query, conn); conn.Open(); MySqlDataReader MyDataReader; MyDataReader = myCommand.ExecuteReader(); while (MyDataReader.Read()) { resultList.Add(MyDataReader.GetString(0)); //Получаем строку } MyDataReader.Close(); conn.Close(); return(resultList); }
private void edit_poezd_Load(object sender, EventArgs e) { label1.Text = "ID: " + transport.idedit_poezd; //ДЕЛАЕМ ЗАПРОС К БД MySqlConnection conn = new MySqlConnection(Form1.connStr); // устанавливаем соединение с БД conn.Open(); // запрос string auth = "SELECT * FROM Poezd WHERE ID_Poezda = '" + transport.idedit_poezd + "'"; try { MySqlCommand commandauth = new MySqlCommand(auth, conn); // string name = commandauth.ExecuteScalar().ToString(); MySqlDataReader MyDataReader; MyDataReader = commandauth.ExecuteReader(); while (MyDataReader.Read()) { textBox2.Text = MyDataReader.GetString(1); textBox3.Text = MyDataReader.GetString(2); } MyDataReader.Close(); // закрываем соединение с БД conn.Close(); } catch { } }
private void button1_Click(object sender, EventArgs e) { if (MessageBox.Show("Сохранить изменения?", "ЖД Вокзал", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { //начинаем запрос try { MySqlConnection conn = new MySqlConnection(Form1.connStr); // устанавливаем соединение с БД conn.Open(); string add = "UPDATE Poezd SET " + "Kolichestvo_vagonov = '" + textBox2.Text + "', " + "Kolichestvo_mest = '" + textBox3.Text + "' WHERE " + "ID_Poezda = '" + transport.idedit_poezd + "'"; MySqlCommand adda = new MySqlCommand(add, conn); // MySqlCommand insrt = new MySqlCommand(insert, conn); MySqlDataReader MyDataReader; MyDataReader = adda.ExecuteReader(); while (MyDataReader.Read()) { } MyDataReader.Close(); conn.Close(); MessageBox.Show("Поезд отредактирован!", "ЖД Вокзал", MessageBoxButtons.OK, MessageBoxIcon.Information); Close(); } catch { MessageBox.Show("Ошибка редактирования!", "ЖД Вокзал", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
public int MySql_Num_Rows(string CommandText) { int n = 0; try { con.Open(); MySqlCommand myCommand = new MySqlCommand(CommandText, con); MySqlDataReader MyDataReader; MyDataReader = myCommand.ExecuteReader(); //SELECT COUNT(*) FROM table while (MyDataReader.Read()) { n++; } MyDataReader.Close(); } catch (MySqlException) { } finally { con.Close(); } return(n); }
protected void Page_Load(object sender, EventArgs e) { string RoomID = Request.Url.Query.ToString().Substring(1); Label2.Text = RoomID; System.Data.SqlClient.SqlConnection MyConnection; System.Data.SqlClient.SqlCommand MyCommand; System.Data.SqlClient.SqlDataReader MyDataReader; MyConnection = new System.Data.SqlClient.SqlConnection("Data Source=co-web-3.lboro.ac.uk;Initial Catalog=team17;User ID=team17;Password=g6g88fcv"); MyConnection.Open(); MyCommand = new System.Data.SqlClient.SqlCommand(); MyCommand.Connection = MyConnection; MyCommand.CommandText = "SELECT Capacity FROM Room WHERE RoomID = '" + RoomID + "' "; MyDataReader = MyCommand.ExecuteReader(); string nocap = ""; while (MyDataReader.Read()) { nocap = MyDataReader.GetSqlValue(0).ToString(); } MyDataReader.Close(); MyDataReader = null; Label3.Text = nocap; NoStudentsValidation.MaximumValue = nocap; NoStudentsValidation.ErrorMessage = "Number of Students must be between 1 and " + nocap + "."; }
protected void DropDownListSelectCandidate_SelectedIndexChanged(object sender, EventArgs e) { buttonActive(false, true, false, true, false, true); SqlConnection sqlConn = new SqlConnection(myConnStr); SqlCommand cmd = new SqlCommand("select * from CandidateTable where CandidateId='" + DropDownListSelectCandidate.SelectedValue + "'", sqlConn); SqlDataReader MyDataReader; try { sqlConn.Open(); MyDataReader = cmd.ExecuteReader(); MyDataReader.Read(); TextBoxCandidateId.Text = MyDataReader["CandidateId"].ToString(); TextBoxCandidateFirstName.Text = MyDataReader["CandidateFName"].ToString(); TextBoxCandidateLastName.Text = MyDataReader["CandidateLName"].ToString(); DropDownListDepartment.Text = MyDataReader["CandidateDepartment"].ToString(); TextBoxCandidateCode.Text = MyDataReader["CandidateCode"].ToString(); //Response.Write("<script language='javascript'> alert('Database connection openned');</script>"); } catch (Exception er) { Response.Write("<script language='javascript'> alert('Database connection failed');</script>"); //Response.Write("<script language='javascript'> alert('Customer not found!');</script>"); } finally { sqlConn.Close(); // Response.Write("<script language='javascript'> alert('Database connection closed');</script>"); } }
protected void ButtonEditStaff_Click(object sender, EventArgs e) { buttonActive(true, false, false, false, true); SqlConnection sqlConn = new SqlConnection(myConnStr); SqlCommand cmd = new SqlCommand("select * from DepartmentTable where DepartmentId='" + DropDownListSelectDepartment.SelectedValue + "'", sqlConn); SqlDataReader MyDataReader; try { sqlConn.Open(); MyDataReader = cmd.ExecuteReader(); MyDataReader.Read(); TextBoxDepartmentId.Text = MyDataReader["DepartmentId"].ToString(); TextBoxDepartmentName.Text = MyDataReader["DepartmentName"].ToString(); //Response.Write("<script language='javascript'> alert('Database connection openned');</script>"); } catch (Exception er) { Response.Write("<script language='javascript'> alert('Database connection failed');</script>"); //Response.Write("<script language='javascript'> alert('Customer not found!');</script>"); } finally { sqlConn.Close(); // Response.Write("<script language='javascript'> alert('Database connection closed');</script>"); } }
// Retourne le total par station public static Dictionary <int, double> getMoyenne() { Dictionary <int, double> result = new Dictionary <int, double>(); if (!connection) { setConnection(); if (!connection) { return(result); } } //Desc de la table donnees OdbcCommand MyCommand = new OdbcCommand("select station, avg(available + free) from donnees where valid='1' group by station;", MyConnection); OdbcDataReader MyDataReader; MyDataReader = MyCommand.ExecuteReader(); Console.WriteLine("Executed : " + MyDataReader.RecordsAffected); while (MyDataReader.Read()) { result[MyDataReader.GetInt32(0)] = MyDataReader.GetDouble(1); } //Close all resources MyDataReader.Close(); return(result); }
// Renvoie le details des stations public static ArrayList getStationsDetails() { ArrayList result = new ArrayList(); if (!connection) { setConnection(); if (!connection) { return(result); } } //Desc de la table donnees OdbcCommand MyCommand = new OdbcCommand("desc stations;", MyConnection); OdbcDataReader MyDataReader; MyDataReader = MyCommand.ExecuteReader(); ArrayList header = new ArrayList(); while (MyDataReader.Read()) { if (string.Compare(MyConnection.Driver, "myodbc3.dll") == 0) { header.Add(MyDataReader.GetString(0)); //Supported only by MyODBC 3.5 } } //Fetch MyCommand.CommandText = "select * from stations;"; MyDataReader.Close(); MyDataReader = MyCommand.ExecuteReader(); Console.WriteLine("Executed : " + MyDataReader.RecordsAffected); while (MyDataReader.Read()) { Dictionary <string, string> temp = new Dictionary <string, string>(); if (string.Compare(MyConnection.Driver, "myodbc3.dll") == 0) { for (int i = 0; i < header.Count; i++) { if (MyDataReader.GetString(i) != "") { temp.Add(header[i] as string, MyDataReader.GetString(i)); } } } result.Add(temp); } //Close all resources MyDataReader.Close(); //MyConnection.Close(); return(result); }
protected void titles1() { System.Data.SqlClient.SqlConnection MyConnection; System.Data.SqlClient.SqlCommand MyCommand; System.Data.SqlClient.SqlDataReader MyDataReader; MyConnection = new System.Data.SqlClient.SqlConnection("Data Source=co-web-3.lboro.ac.uk;Initial Catalog=team17;User ID=team17;Password=g6g88fcv"); MyConnection.Open(); MyCommand = new System.Data.SqlClient.SqlCommand(); MyCommand.Connection = MyConnection; MyCommand.CommandText = "SELECT RequestID FROM Request WHERE (Status = 'Pending') AND (UserID = '" + Session["login_name"] + "') AND (RoundID IN (SELECT RoundID From Round WHERE (SemesterID = '" + DropDownList1.SelectedValue + "')))"; MyDataReader = MyCommand.ExecuteReader(); while (MyDataReader.Read()) { if (MyDataReader.GetSqlValue(0).ToString() == "Null") { Label2.Visible = false; } else { Label2.Visible = true; } } MyDataReader.Close(); MyDataReader = null; MyCommand.CommandText = "SELECT RequestID FROM Request WHERE (Status = 'Allocated') AND (UserID = '" + Session["login_name"] + "') AND (RoundID IN (SELECT RoundID From Round WHERE (SemesterID = '" + DropDownList1.SelectedValue + "')))"; MyDataReader = MyCommand.ExecuteReader(); while (MyDataReader.Read()) { if (MyDataReader.GetSqlValue(0).ToString() == "Null") { Label1.Visible = false; } else { Label1.Visible = true; } } MyDataReader.Close(); MyDataReader = null; MyCommand.CommandText = "SELECT RequestID FROM Request WHERE (Status = 'Denied') AND (UserID = '" + Session["login_name"] + "') AND (RoundID IN (SELECT RoundID From Round WHERE (SemesterID = '" + DropDownList1.SelectedValue + "')))"; MyDataReader = MyCommand.ExecuteReader(); while (MyDataReader.Read()) { if (MyDataReader.GetSqlValue(0).ToString() == "Null") { Label3.Visible = false; } else { Label3.Visible = true; } } MyDataReader.Close(); MyDataReader = null; }
private void Window_Loaded(object sender, RoutedEventArgs e) { outt_TPicker.Value = Convert.ToDateTime(Login.etimehh + ":" + Login.etimemm); using (OdbcCommand MyCommand = new OdbcCommand("select date_year,date_month,date_day from tms_logsheet where logsheet_id='" + lgid + "'", Connection.MyConnection)) { OdbcDataReader MyDataReader; MyDataReader = MyCommand.ExecuteReader(); MyDataReader.Read(); load_lab.Content = "You haven't sign-out on " + (MyDataReader.GetInt32(2).ToString()) + "/" + (MyDataReader.GetInt32(1).ToString()) + "/" + (MyDataReader.GetInt32(0).ToString()) + "."; MyDataReader.Close(); } }
static void Main(string[] args) { MySqlConnection myConnection = new MySqlConnection("Database = vlad_m; Data Source = 192.168.27.79; User Id = vlad_m; charset=cp1251;default command timeout = 999; Password=vlad19957"); MySqlCommand myCommand = new MySqlCommand(); MySqlDataReader MyDataReader; OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=dBASE 5.0;Data Source=D:\\Alex\\RNCB\\exp_db_gis"); myCommand.Connection = myConnection; myConnection.Open(); conn.Open(); string s = DateTime.Now.ToString("yyyyMMdd" + "_9103006160.DBF"); OleDbCommand dbf = new OleDbCommand(string.Format("CREATE TABLE [" + s + "] (ELS VARCHAR(20),PAYERIDENT VARCHAR(11), FIO VARCHAR(50), LS VARCHAR(11), STREET VARCHAR(25), BUILDING VARCHAR(10), FLAT VARCHAR(10), SUM1 NUMERIC(10,2), SERVICECOD VARCHAR(2))"), conn); dbf.Prepare(); dbf.ExecuteNonQuery(); // myCommand.CommandText = string.Format("UPDATE rncb,id_ls set rncb.jky = id_ls.ls_jky where rncb.ls = id_ls.id"); //myCommand.Prepare();//подготавливает строку // myCommand.ExecuteNonQuery();//выполняет запрос myCommand.CommandText = string.Format("select " + "id_ls.ls_jky, rncb.PAYERIDENT, rncb.FIO, rncb.LS, rncb.STREET, rncb.BUILDING, rncb.FLAT, rncb.SUM1, rncb.SERVICECOD " + "from rncb " + "left OUTER JOIN id_ls on rncb.LS = id_ls.id " + "order by 4; "); myCommand.Prepare();//подготавливает строку MyDataReader = myCommand.ExecuteReader(); while (MyDataReader.Read()) { dbf.CommandText = string.Format("INSERT INTO [" + s + "] (ELS,PAYERIDENT,FIO,LS,STREET,BUILDING,FLAT,SUM1,SERVICECOD) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')", MySqlHelper.EscapeString(MyDataReader.GetValue(0).ToString()), MySqlHelper.EscapeString(MyDataReader.GetValue(1).ToString()), MySqlHelper.EscapeString(MyDataReader.GetValue(2).ToString()), MySqlHelper.EscapeString(MyDataReader.GetValue(3).ToString()), MySqlHelper.EscapeString(MyDataReader.GetValue(4).ToString()), MySqlHelper.EscapeString(MyDataReader.GetValue(5).ToString()), MySqlHelper.EscapeString(MyDataReader.GetValue(6).ToString()), MySqlHelper.EscapeString(MyDataReader.GetValue(7).ToString()), MySqlHelper.EscapeString(MyDataReader.GetValue(8).ToString())); dbf.Prepare(); dbf.ExecuteNonQuery(); } MyDataReader.Close(); MyDataReader.Close(); conn.Close(); }
// Initialize the connection to the DB private static void setConnection() { try { //Connect to MySQL using MyODBC MyConnection = new OdbcConnection(MyConString); MyConnection.Open(); connection = true; tailles = new Dictionary <int, int>(); OdbcCommand MyCommand = new OdbcCommand("select id,max(total) from stations group by id;", MyConnection); //OdbcCommand MyCommand = new OdbcCommand( "select station, max(free+available) from donnees where free !=\"\" group by station;", MyConnection ); OdbcDataReader MyDataReader; MyDataReader = MyCommand.ExecuteReader(); Console.WriteLine("Executed : " + MyDataReader.RecordsAffected); while (MyDataReader.Read()) { int valeur = 0; int station = MyDataReader.GetInt32(0); //int hour = MyDataReader.GetInt32(1); try { valeur = MyDataReader.GetInt32(1); } catch (Exception e) { Console.WriteLine("Pas de base : " + e.Message); continue; } tailles.Add(station, valeur); } //Close all resources MyDataReader.Close(); } catch (OdbcException MyOdbcException)//Catch any ODBC exception .. { connection = false; for (int i = 0; i < MyOdbcException.Errors.Count; i++) { MessageBox.Show("Aucune connection à la base de données n'a pu être établie"); Console.Write("ERROR #" + i + "\n" + "Message: " + MyOdbcException.Errors[i].Message + "\n" + "Native: " + MyOdbcException.Errors[i].NativeError.ToString() + "\n" + "Source: " + MyOdbcException.Errors[i].Source + "\n" + "SQL: " + MyOdbcException.Errors[i].SQLState + "\n"); } } }
// Retourne les vecteurs pour les jours ouvres public static void getRemplissageByHourOuvresHisto(DateTime start, DateTime end) { Dictionary <int, Dictionary <int, KeyValuePair <double, double> > > result = new Dictionary <int, Dictionary <int, KeyValuePair <double, double> > >(); if (!connection) { setConnection(); } //Desc de la table donnees string s = " and date >= " + convertToTimestamp(start) + " and date <= " + convertToTimestamp(end) + " "; s += "and day < 6 "; OdbcCommand MyCommand = new OdbcCommand("select station as Station, hour as Hour, cast(avg(available) * 100 as unsigned) as Valeur, cast(std(available) * 100 as unsigned) as Variance from donnees where valid='1' and free!=\"\" " + s + "group by station, hour;", MyConnection); OdbcDataReader MyDataReader; MyDataReader = MyCommand.ExecuteReader(); Console.WriteLine("Executed : " + MyDataReader.RecordsAffected); while (MyDataReader.Read()) { int valeur = 0; int station = MyDataReader.GetInt32(0); int hour = MyDataReader.GetInt32(1); int variance = 0; try { valeur = MyDataReader.GetInt32(2); } catch (Exception e) { Console.WriteLine("Error : " + e.Message); continue; } try { variance = MyDataReader.GetInt32(3); } catch (Exception e) { Console.WriteLine("Error : " + e.Message); continue; } if (!result.ContainsKey(station)) { result[station] = new Dictionary <int, KeyValuePair <double, double> >(); } result[station][hour] = new KeyValuePair <double, double>((valeur / 100.0) / (double)tailles[station], (variance / 100.0) / (double)tailles[station]); } //Close all resources MyDataReader.Close(); statsTabHeureOuvre = result; }
// Retourne les vecteurs par jour public static Dictionary <int, Dictionary <int, double> > getRemplissageByDay(DateTime start, DateTime end) { Dictionary <int, Dictionary <int, double> > result = new Dictionary <int, Dictionary <int, double> >(); if (!connection) { setConnection(); if (!connection) { return(result); } } //Desc de la table donnees string s = " and date >= " + convertToTimestamp(start) + " and date <= " + convertToTimestamp(end) + " "; OdbcCommand MyCommand = new OdbcCommand("select station as Station, day as Day, cast(avg(available) * 100 as unsigned) as Valeur from donnees where valid='1' and free!=\"\" " + s + "group by station, day;", MyConnection); OdbcDataReader MyDataReader; MyDataReader = MyCommand.ExecuteReader(); Console.WriteLine("Executed : " + MyDataReader.RecordsAffected); while (MyDataReader.Read()) { int valeur = 0; int station = MyDataReader.GetInt32(0); int hour = MyDataReader.GetInt32(1); try { valeur = MyDataReader.GetInt32(2); } catch (Exception e) { Console.WriteLine("Error : " + e.Message); continue; } if (!result.ContainsKey(station)) { result[station] = new Dictionary <int, double>(); } result[station][hour] = valeur / 100.0; result[station][hour] = result[station][hour] / (double)tailles[station]; } //Close all resources MyDataReader.Close(); return(result); }
public void Zapros(string CommandText) { MySqlCommand myCommand = new MySqlCommand(); MySqlDataReader MyDataReader; MySqlConnection myConnection = new MySqlConnection(CONNECT); listSpravka.ItemsSource = null; myCommand = new MySqlCommand(CommandText, myConnection); myConnection.Open(); MyDataReader = myCommand.ExecuteReader(); while (MyDataReader.Read()) { norma.Add(new Norma(MyDataReader.GetInt32(0), MyDataReader.GetInt32(1), MyDataReader.GetString(2))); } MyDataReader.Close(); }
// Effectue les requetes private static Dictionary <int, Dictionary <int, KeyValuePair <double, double> > > sendRequest(String query, int select) { Dictionary <int, Dictionary <int, KeyValuePair <double, double> > > result = new Dictionary <int, Dictionary <int, KeyValuePair <double, double> > >(); if (!connection) { setConnection(); if (!connection) { return(result); } } //Console.WriteLine("\n !!! success, connected successfully !!!\n"); ////Display connection information //Console.WriteLine("Connection Information:"); //Console.WriteLine("\tConnection String:" + MyConnection.ConnectionString); //Console.WriteLine("\tConnection Timeout:" + MyConnection.ConnectionTimeout); //Console.WriteLine("\tDatabase:" + MyConnection.Database); //Console.WriteLine("\tDataSource:" + MyConnection.DataSource); //Console.WriteLine("\tDriver:" + MyConnection.Driver); //Console.WriteLine("\tServerVersion:" + MyConnection.ServerVersion); //Desc de la table donnees OdbcCommand MyCommand = new OdbcCommand(query, MyConnection); OdbcDataReader MyDataReader; MyDataReader = MyCommand.ExecuteReader(); Console.WriteLine("Executed : " + MyDataReader.RecordsAffected); while (MyDataReader.Read()) { KeyValuePair <double, double> temp1 = new KeyValuePair <double, double>(MyDataReader.GetDouble(1), MyDataReader.GetDouble(2)); Dictionary <int, KeyValuePair <double, double> > temp = new Dictionary <int, KeyValuePair <double, double> >(); temp[select] = temp1; result[MyDataReader.GetInt32(0)] = temp; //result.Add(MyDataReader.GetInt32(0), temp); } //Close all resources MyDataReader.Close(); //MyConnection.Close(); return(result); }
private void edit_usr_Load(object sender, EventArgs e) { label1.Text = "ID: " + sotrudniki.idedit; //ДЕЛАЕМ ЗАПРОС К БД MySqlConnection conn = new MySqlConnection(Form1.connStr); // устанавливаем соединение с БД conn.Open(); // запрос string auth = "SELECT * FROM Sotrudnic WHERE ID_Sotrudnica = '" + sotrudniki.idedit + "'"; try { MySqlCommand commandauth = new MySqlCommand(auth, conn); // string name = commandauth.ExecuteScalar().ToString(); MySqlDataReader MyDataReader; MyDataReader = commandauth.ExecuteReader(); while (MyDataReader.Read()) { // id = MyDataReader.GetInt32(0); surname_addusr = MyDataReader.GetString(1); name_addusr = MyDataReader.GetString(2); otchestvo_addusr = MyDataReader.GetString(3); phones_addusr = MyDataReader.GetString(4); login_addusr = MyDataReader.GetString(5); // podrzdid = MyDataReader.GetInt32(7); role_addusr = MyDataReader.GetString(7); } MyDataReader.Close(); // закрываем соединение с БД conn.Close(); textBox2.Text = surname_addusr; textBox1.Text = name_addusr; textBox6.Text = otchestvo_addusr; textBox5.Text = phones_addusr; textBox3.Text = login_addusr; comboBox1.SelectedIndex = Convert.ToInt32(role_addusr); } catch { } }
private void toolStripButton1_Click(object sender, EventArgs e) { int index = dataGridView1.CurrentCell.RowIndex; string ind = Convert.ToString(dataGridView1.Rows[index].Cells[0].Value); try { if (ind != Form1.id.ToString()) { if (MessageBox.Show("Удалить сотрудника?\nОтменить данное действие будет невозможно.", "ЖД Вокзал", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { MySqlConnection conn = new MySqlConnection(Form1.connStr); // устанавливаем соединение с БД conn.Open(); string add = "DELETE FROM Sotrudnic WHERE ID_Sotrudnica = '" + ind + "'"; MySqlCommand adda = new MySqlCommand(add, conn); MySqlDataReader MyDataReader; MyDataReader = adda.ExecuteReader(); while (MyDataReader.Read()) { } MyDataReader.Close(); conn.Close(); MessageBox.Show("Сотрудник удален!", "ЖД Вокзал", MessageBoxButtons.OK, MessageBoxIcon.Information); refreshing(); // Close(); } else { MessageBox.Show("Удаление отменено!", "ЖД Вокзал", MessageBoxButtons.OK, MessageBoxIcon.Information); } } else { MessageBox.Show("Нельзя удалить самого себя!", "ЖД Вокзал", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch { MessageBox.Show("Ошибка удаления!", "ЖД Вокзал", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public bool WebAuth(string login, string password, AccessLevel accl) { if (login != null && password != null) { MySqlDataReader MyDataReader; cmd.CommandText = "SELECT login, password, access_level FROM `accounts`;"; MyDataReader = cmd.ExecuteReader(); while (MyDataReader.Read()) { int _access_level = MyDataReader.GetInt32(2); string _login = MyDataReader.GetString(0); string _password = MyDataReader.GetString(1); if (_login == login && _password == password) { if (accl == AccessLevel.Admin) { MyDataReader.Close(); if (_access_level == ((int)AccessLevel.Admin)) { return(true); } else { return(false); } } else { MyDataReader.Close(); return(true); } } } if (!MyDataReader.IsClosed) { MyDataReader.Close(); } } return(false); }
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { string id_po = ""; string[] idpomas = new string[5]; if (comboBox1.SelectedItem.ToString() != "") { idpomas = comboBox1.SelectedItem.ToString().Split('№'); id_po = idpomas[1]; } try { MySqlConnection conn = new MySqlConnection(Form1.connStr); // устанавливаем соединение с БД conn.Open();// string add = "SELECT * FROM Poezd WHERE ID_Poezda = '" + id_po + "'"; MySqlCommand adda = new MySqlCommand(add, conn); // MySqlCommand insrt = new MySqlCommand(insert, conn); MySqlDataReader MyDataReader; MyDataReader = adda.ExecuteReader(); while (MyDataReader.Read()) { kolvovagonov = MyDataReader.GetString(1); kolvomest = MyDataReader.GetString(2); } // MessageBox.Show(id_po, "ЖД Вокзал", MessageBoxButtons.OK, MessageBoxIcon.Information); MyDataReader.Close(); conn.Close(); label10.Text = "Вагонов: " + kolvovagonov + " Мест: " + kolvomest + ""; // MessageBox.Show("Задание успешно добавлено!", "JobReciever", MessageBoxButtons.OK, MessageBoxIcon.Information); // Close(); } catch (Exception msg) { MessageBox.Show("Ошибка загрузки списка!\n" + msg, "ЖД Вокзал", MessageBoxButtons.OK, MessageBoxIcon.Error); } }