示例#1
0
        public override void Save(IEntity p)
        {
            OpenConnection();
            MySql.Data.MySqlClient.MySqlTransaction tr = m_connection.BeginTransaction();
            User e = (User)p;

            try
            {
                MySql.Data.MySqlClient.MySqlCommand aCommand = new MySql.Data.MySqlClient.MySqlCommand(e.GetInsertSQL(), m_connection);
                aCommand.Transaction = tr;
                aCommand.ExecuteNonQuery();
                aCommand.CommandText = e.GetMaximumIDSQL();
                e.ID = Convert.ToInt32(aCommand.ExecuteScalar());
                foreach (string kys in e.FORM_ACCESS_LIST.Keys)
                {
                    aCommand.CommandText = e.FORM_ACCESS_LIST[kys].GetInsertSQL();
                    aCommand.ExecuteNonQuery();
                    aCommand.CommandText       = e.FORM_ACCESS_LIST[kys].GetMaximumIDSQL();
                    e.FORM_ACCESS_LIST[kys].ID = Convert.ToInt32(aCommand.ExecuteScalar());
                }
                tr.Commit();
            }
            catch (Exception x)
            {
                tr.Rollback();
                e.ID = 0;
                throw new Exception(getErrorMessage(x));
            }
            finally
            {
                m_connection.Close();
            }
        }
示例#2
0
        private bool isExist(int userid, string name, Type type)
        {
            string get = String.Format(@"select count(*) from table_usersettings where user_id = {0}
                        and us_name = '{1}' and us_type = '{2}' ", userid, name, type.ToString());

            m_cmd.CommandText = get;
            int count = Convert.ToInt32(m_cmd.ExecuteScalar());

            return(count > 0);
        }
示例#3
0
        Boolean vWait = true; //Aguarda backup do banco antes do backup de arquivos.

        public frmBackup()
        {
            InitializeComponent();

            try
            {   // Abrir o arquivo para autenticar o servidor.
                using (StreamReader sr = new StreamReader(@"C:\Program Files (x86)\GIPP\autentication"))
                {
                    // Ler o conteudo do arquivo para uma string.
                    String line = sr.ReadToEnd();
                    connection = new MySql.Data.MySqlClient.MySqlConnection(line);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Arquivo não pode ser lido: " + ex.Message, "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            this.notifyIcon.ContextMenuStrip = new System.Windows.Forms.ContextMenuStrip(); //Cria e configura o icone de notificação do Backup.
            this.notifyIcon.ContextMenuStrip.Items.Add("Mostrar");
            this.notifyIcon.ContextMenuStrip.Items.Add("Ocultar");
            this.notifyIcon.ContextMenuStrip.Items.Add("Fechar");
            this.notifyIcon.ContextMenuStrip.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.notifyIcon_MenuClick);

            cmd.Connection = connection;

            try
            {
                connection.Open();
                cmd.CommandText  = "SELECT data_last_backup FROM system_checks WHERE id = '1'";
                lblBakData.Text  = (string)cmd.ExecuteScalar();
                cmd.CommandText  = "SELECT system_last_backup FROM system_checks WHERE id = '1'";
                lblBakFiles.Text = (string)cmd.ExecuteScalar();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro! " + ex.Message);
            }
            finally
            {
                connection.Close();
                connection.Dispose();
            }

            lblFiles.Text = "Verificando backup...";

            vError          = false;
            u               = new Thread(uThreadProcess);
            cmbBkpTime.Text = "24"; //A Thread 'u' será iniciada dentro de cmbBkpTime_SelectedIndexChanged.
            vTime           = "24";
        }
示例#4
0
        public override void Save(IEntity en)
        {
            OpenConnection();
            MySql.Data.MySqlClient.MySqlTransaction trans    = m_connection.BeginTransaction();
            MySql.Data.MySqlClient.MySqlCommand     aCommand = new MySql.Data.MySqlClient.MySqlCommand();
            aCommand.Connection  = m_connection;
            aCommand.Transaction = trans;
            Part e = (Part)en;

            try
            {
                aCommand.CommandText = e.GetInsertSQL();
                this.SavePicture(e.PICTURE, e.CODE);
                aCommand.ExecuteNonQuery();
                aCommand.CommandText = e.GetMaximumIDSQL();
                e.ID = Convert.ToInt32(aCommand.ExecuteScalar());
                //add Base Conversion--------------------
                UnitConversion unit = new UnitConversion();
                unit.BARCODE         = e.BARCODE;
                unit.CONVERSION_QTY  = 1;
                unit.CONVERSION_UNIT = e.UNIT;
                unit.COST_PRICE      = e.COST_PRICE;
                unit.ORIGINAL_QTY    = 1;
                unit.PART            = e;
                unit.SELL_PRICE      = e.SELL_PRICE;
                e.UNIT_CONVERSION_LIST.Add(unit);
                //---------------------------------------
                foreach (UnitConversion uc in e.UNIT_CONVERSION_LIST)
                {
                    aCommand.CommandText = uc.GetInsertSQL();
                    aCommand.ExecuteNonQuery();
                    aCommand.CommandText = uc.GetMaximumIDSQL();
                    uc.ID = Convert.ToInt32(aCommand.ExecuteScalar());
                }
                trans.Commit();
            }
            catch (Exception x)
            {
                trans.Rollback();
                en.SetID(0);
                foreach (UnitConversion uc in e.UNIT_CONVERSION_LIST)
                {
                    uc.ID = 0;
                }
                throw new Exception(getErrorMessage(x));
            }
            finally
            {
                m_connection.Close();
            }
        }
示例#5
0
 public static void Save(MySql.Data.MySqlClient.MySqlCommand cmd, VendorBalance sc)
 {
     cmd.CommandText = sc.GetInsertSQL();
     cmd.ExecuteNonQuery();
     cmd.CommandText = VendorBalance.SelectMaxIDSQL();
     sc.ID           = Convert.ToInt32(cmd.ExecuteScalar());
     foreach (VendorBalanceEntry sce in sc.VENDOR_BALANCE_ENTRIES)
     {
         cmd.CommandText = sce.GetInsertSQL();
         cmd.ExecuteNonQuery();
         cmd.CommandText = VendorBalanceEntry.SelectMaxIDSQL();
         sce.ID          = Convert.ToInt32(cmd.ExecuteScalar());
     }
 }
示例#6
0
 public static void Save(MySql.Data.MySqlClient.MySqlCommand cmd, StockCard sc)
 {
     cmd.CommandText = sc.GetInsertSQL();
     cmd.ExecuteNonQuery();
     cmd.CommandText = StockCard.SelectMaxIDSQL();
     sc.ID           = Convert.ToInt32(cmd.ExecuteScalar());
     foreach (StockCardEntry sce in sc.STOCK_CARD_ENTRIES)
     {
         cmd.CommandText = sce.GetInsertSQL();
         cmd.ExecuteNonQuery();
         cmd.CommandText = StockCardEntry.SelectMaxIDSQL();
         sce.ID          = Convert.ToInt32(cmd.ExecuteScalar());
     }
 }
示例#7
0
            /// <summary>
            /// Для выполнения запросов к MySQL с возвращением 1 параметра.
            /// </summary>
            /// <param name="sql">Текст запроса к базе данных</param>
            /// <param name="connection">Строка подключения к базе данных</param>
            /// <returns>Возвращает значение при успешном выполнении запроса, текст ошибки - при ошибке.</returns>
            public static MyResult SqlScalar(string sql, string connection)
            {
                MyResult result = new MyResult();

                try
                {
                    MySql.Data.MySqlClient.MySqlConnection connRC = new MySql.Data.MySqlClient.MySqlConnection(connection);
                    MySql.Data.MySqlClient.MySqlCommand    commRC = new MySql.Data.MySqlClient.MySqlCommand(sql, connRC);
                    connRC.Open();
                    try
                    {
                        result.ResultText = commRC.ExecuteScalar().ToString();
                        result.HasError   = false;
                    }
                    catch (Exception ex)
                    {
                        result.ErrorText = ex.Message;
                        result.HasError  = true;
                    }
                    connRC.Close();
                }
                catch (Exception ex)//Этот эксепшн на случай отсутствия соединения с сервером.
                {
                    result.ErrorText = ex.Message;
                    result.HasError  = true;
                }
                return(result);
            }
示例#8
0
        public void Add(Character character)
        {
            using (var con = new MySql.Data.MySqlClient.MySqlConnection(connectionString))
            {
                var cmd = new MySql.Data.MySqlClient.MySqlCommand(
                    "INSERT INTO Characters(UserID, Name, Description, Level) " +
                    "VALUES(@UserID, @Name, @Description, @Level)"
                    , con
                    );
                cmd.Parameters.AddWithValue("@UserID", character.UserID);
                cmd.Parameters.AddWithValue("@Name", character.Name);
                cmd.Parameters.AddWithValue("@Description", character.Description);
                cmd.Parameters.AddWithValue("@Level", character.Level);

                con.Open();
                cmd.ExecuteNonQuery();

                cmd = new MySql.Data.MySqlClient.MySqlCommand("SELECT LAST_INSERT_ID()", con);

                var CharacterID = Convert.ToInt32(cmd.ExecuteScalar());

                foreach (var specialty in character.Specialties)
                {
                    AddCharacterSpecialty(CharacterID, specialty);
                }
                con.Close();
            }
        }
示例#9
0
        private void buttonTest_Click(object sender, EventArgs e)
        {
            NameTest = textBoxNameTest.Text;
            string Connect = "Database=u0354899_diplom;Data Source=31.31.196.162;User Id=u0354899_vlad;Password=vlad19957;charset=cp1251";

            MySql.Data.MySqlClient.MySqlConnection myConnection = new MySql.Data.MySqlClient.MySqlConnection(Connect);
            MySql.Data.MySqlClient.MySqlCommand    myCommand    = new MySql.Data.MySqlClient.MySqlCommand();
            myConnection.Open();
            myCommand.Connection  = myConnection;
            myCommand.CommandText = string.Format("SELECT id FROM teacher WHERE login='******'", Main.LoginGlobal);
            myCommand.Prepare();                           //подготавливает строку
            myCommand.ExecuteNonQuery();                   //выполняет запрос
            int idtecher = (int)myCommand.ExecuteScalar(); //результат запроса

            myCommand.CommandText = string.Format("INSERT INTO tests (idteacher,NameTest) " + "VALUES('{0}','{1}')", idtecher, NameTest);
            myCommand.Prepare();                     //подготавливает строку
            myCommand.ExecuteNonQuery();             //выполняет запрос
            idtests = (int)myCommand.LastInsertedId; //получаем id
            if (CheckPDF == true)
            {
                checkFolderFtp(url);
                WebClient myWebClient = new WebClient();
                Uri       ftp_path    = new Uri("ftp://*****:*****@31.31.196.162" + url + fileName); // file.txt - файл, который будет в конечном итоге залит; FTPLOGIN - логин к FTP; PASSWORD - пароль к FTP; LOGIN и PASSWORD разделяются двоеточием.
                myWebClient.UploadFile(ftp_path, urlName);                                                       // anyfile.txt - загружаемый файл на FTP; C:/Files... - путь к загружаемому файлу; ftp_path - конечный путь и имя файла, которое будет на FTP сервере.
                string urlFile = "http://www.imtis.ru/pdf/" + Main.LoginGlobal + "/" + fileName;
                myCommand.CommandText = string.Format("UPDATE tests SET pdf = '{0}' WHERE id = '{1}'", urlFile, idtests);
                myCommand.Prepare();         //подготавливает строку
                myCommand.ExecuteNonQuery(); //выполняет запрос
            }
            myConnection.Close();
            CreatTest test = new CreatTest();

            test.Show();
            this.Hide();
        }
示例#10
0
        public Stream ShowEmpImage1(Int32 empno)
        {
            String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();

            conn            = new MySql.Data.MySqlClient.MySqlConnection(connString);
            queryStr        = "";
            queryStr        = "SELECT attachement FROM email WHERE id = @ID   ";
            cmd             = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@ID", empno);

            conn.Open();
            object img = cmd.ExecuteScalar();

            try
            {
                return(new MemoryStream((byte[])img));
            }
            catch
            {
                return(null);
            }
            finally
            {
                conn.Close();
            }
        }
        public Stream ShowEmpImage3(Int32 empno, String empno1)
        {
            String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();

            conn            = new MySql.Data.MySqlClient.MySqlConnection(connString);
            queryStr        = "";
            queryStr        = "SELECT imagepram FROM param WHERE codeuser= @CD AND numzone= @NM";
            cmd             = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@CD", empno);
            cmd.Parameters.AddWithValue("@NM", empno1);

            conn.Open();
            object img = cmd.ExecuteScalar();

            try
            {
                return(new MemoryStream((byte[])img));
            }
            catch
            {
                return(null);
            }
            finally
            {
                conn.Close();
            }
        }
示例#12
0
            /// <summary>
            /// Для выполнения запросов к MySQL с возвращением 1 параметра.
            /// </summary>
            /// <param name="sql">Текст запроса к базе данных</param>
            /// <param name="connection">Строка подключения к базе данных</param>
            /// <returns>Возвращает значение при успешном выполнении запроса, текст ошибки - при ошибке.</returns>
            public static MyResult SqlScalar(string sql)
            {
                MyResult result = new MyResult();

                try
                {
                    string connection = "Database=u0354899_diplom;Data Source=31.31.196.162;User Id=u0354899_vlad;Password=vlad19957;charset=cp1251";
                    MySql.Data.MySqlClient.MySqlConnection connRC = new MySql.Data.MySqlClient.MySqlConnection(connection);
                    MySql.Data.MySqlClient.MySqlCommand    commRC = new MySql.Data.MySqlClient.MySqlCommand(sql, connRC);
                    connRC.Open();
                    try
                    {
                        result.ResultText = commRC.ExecuteScalar().ToString();
                        result.HasError   = false;
                    }
                    catch (Exception ex)
                    {
                        result.ErrorText = ex.Message;
                        result.HasError  = true;
                    }
                    connRC.Close();
                }
                catch (Exception ex)//Этот эксепшн на случай отсутствия соединения с сервером.
                {
                    result.ErrorText = ex.Message;
                    result.HasError  = true;
                }
                return(result);
            }
示例#13
0
 public static void SaveHeader(MySql.Data.MySqlClient.MySqlCommand cmd, StockCard sc)
 {
     cmd.CommandText = sc.GetInsertSQL();
     cmd.ExecuteNonQuery();
     cmd.CommandText = StockCard.SelectMaxIDSQL();
     sc.ID           = Convert.ToInt32(cmd.ExecuteScalar());
 }
示例#14
0
 public int GetLastInsertedId(string _TableName)
 {
     Command             = Connection.CreateCommand();
     Command.CommandType = System.Data.CommandType.Text;
     Command.CommandText = "SELECT id FROM RemoteControl." + _TableName + " ORDER BY timestamp DESC LIMIT 1";
     return((int)Command.ExecuteScalar());
 }
示例#15
0
 /// <summary>
 /// 执行一条计算查询结果语句,返回查询结果(object)。
 /// </summary>
 /// <param name="SQLString">计算查询结果语句</param>
 /// <returns>查询结果(object)</returns>
 public static object GetSingle(string SQLString, params MySql.Data.MySqlClient.MySqlParameter[] cmdParms)
 {
     using (MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection(connectionString))
     {
         using (MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand())
         {
             try
             {
                 PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                 object obj = cmd.ExecuteScalar();
                 cmd.Parameters.Clear();
                 if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                 {
                     return(null);
                 }
                 else
                 {
                     return(obj);
                 }
             }
             catch (System.Data.OleDb.OleDbException e)
             {
                 throw new Exception(e.Message);
             }
         }
     }
 }
示例#16
0
 /// <summary>
 /// 执行一条计算查询结果语句,返回查询结果(object)。
 /// </summary>
 /// <param name="SQLString">计算查询结果语句</param>
 /// <returns>查询结果(object)</returns>
 public static object GetSingle(string SQLString)
 {
     using (MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection(connectionString))
     {
         using (MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(SQLString, connection))
         {
             try
             {
                 connection.Open();
                 object obj = cmd.ExecuteScalar();
                 if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                 {
                     return(null);
                 }
                 else
                 {
                     return(obj);
                 }
             }
             catch (System.Data.OleDb.OleDbException e)
             {
                 connection.Close();
                 throw new Exception(e.Message);
             }
         }
     }
 }
示例#17
0
        /// <summary>
        /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
        /// </summary>
        /// <param name="strSQL">SQL语句</param>
        /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
        {
            using (MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection(connectionString))
            {
                MySql.Data.MySqlClient.MySqlCommand   cmd         = new MySql.Data.MySqlClient.MySqlCommand(strSQL, connection);
                MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@fs", MySql.Data.MySqlClient.MySqlDbType.Binary);
                myParameter.Value = fs;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    cmd.ExecuteNonQuery();

                    cmd.CommandText = "SELECT @@IDENTITY";
                    int rows = (int)cmd.ExecuteScalar();
                    return(rows);
                }
                catch (System.Data.OleDb.OleDbException E)
                {
                    throw new Exception(E.Message);
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }
示例#18
0
文件: Main.cs 项目: nebosvod/notify
            /// <summary>
            /// Для выполнения запросов к MySQL с возвращением 1 параметра.
            /// </summary>
            /// <param name="sql">Текст запроса к базе данных</param>
            /// <param name="connection">Строка подключения к базе данных</param>
            /// <returns>Возвращает значение при успешном выполнении запроса, текст ошибки - при ошибке.</returns>
            public static MyResult SqlScalar(string sql, string connection)
            {
                MyResult result = new MyResult();
                try
                {
                    MySql.Data.MySqlClient.MySqlConnection connRC = new MySql.Data.MySqlClient.MySqlConnection(connection);
                    MySql.Data.MySqlClient.MySqlCommand commRC = new MySql.Data.MySqlClient.MySqlCommand(sql, connRC);
                    connRC.Open();
                    try
                    {
                        result.ResultText = commRC.ExecuteScalar().ToString();
                        result.HasError = false;
                    }
                    catch (Exception ex)
                    {
                        result.ErrorText = ex.Message;
                        result.HasError = true;

                    }
                    connRC.Close();
                }
                catch (Exception ex)//Этот эксепшн на случай отсутствия соединения с сервером.
                {
                    result.ErrorText = ex.Message;
                    result.HasError = true;
                }
                return result;
            }
示例#19
0
        public int ExecuteScalar(string SqlStatment)
        {
            MySql.Data.MySqlClient.MySqlConnection Cn = new MySql.Data.MySqlClient.MySqlConnection(ConnectionString);
            Cn.Open();
            object result;

            MySql.Data.MySqlClient.MySqlCommand Cmd = new MySql.Data.MySqlClient.MySqlCommand(SqlStatment, Cn);
            try
            {
                result = Cmd.ExecuteScalar();
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                Cn.Close();
            }
            if (result != null && result.ToString() != "")
            {
                return(int.Parse(result.ToString()));
            }
            else
            {
                return(-1);
            }
        }
示例#20
0
        public override void Save(IEntity en)
        {
            Year e = (Year)en;

            OpenConnection();
            MySql.Data.MySqlClient.MySqlTransaction transac = m_connection.BeginTransaction();
            try
            {
                MySql.Data.MySqlClient.MySqlCommand aCommand = new MySql.Data.MySqlClient.MySqlCommand(e.GetInsertSQL(), m_connection);
                aCommand.Transaction = transac;
                aCommand.ExecuteNonQuery();
                aCommand.CommandText = e.GetMaximumIDSQL();
                e.ID = Convert.ToInt32(aCommand.ExecuteScalar());
                e.GeneratePeriods();
                foreach (Period p in e.PERIODS)
                {
                    aCommand.CommandText = p.GetInsertSQL();
                    aCommand.ExecuteNonQuery();
                }
                transac.Commit();
            }
            catch (Exception x)
            {
                transac.Rollback();
                throw new Exception(getErrorMessage(x));
            }
            finally
            {
                m_connection.Close();
            }
        }
示例#21
0
文件: Main.cs 项目: vladu4eg/DiplomPC
 private void button1_Click(object sender, EventArgs e)
 {
     try
     {
         string login   = textBoxLogin.Text;
         string pass    = textBoxPassword.Text;
         string Connect = "Database=u0354899_diplom;Data Source=31.31.196.162;User Id=u0354899_vlad;Password=vlad19957;charset=cp1251";
         MySql.Data.MySqlClient.MySqlConnection myConnection = new MySql.Data.MySqlClient.MySqlConnection(Connect);
         MySql.Data.MySqlClient.MySqlCommand    myCommand    = new MySql.Data.MySqlClient.MySqlCommand();
         myConnection.Open();
         myCommand.Connection  = myConnection;
         myCommand.CommandText = string.Format("SELECT login FROM Student WHERE login='******' AND password='******' ", login, pass); //запрос: если есть такой логин в таблице
         myCommand.Prepare();                                                                                                   //подготавливает строку
         myCommand.ExecuteNonQuery();                                                                                           //выполняет запрос
         LoginGlobal = (string)myCommand.ExecuteScalar();                                                                       //результат запроса
         if (LoginGlobal == login)
         {
             MessageBox.Show("Вы зашли как студент! Скачайте мобильное приложение для студентов.");
         }
         else if (LoginGlobal != login)
         {
             myCommand.CommandText = string.Format("SELECT login FROM teacher WHERE login='******' AND password='******' ", login, pass); //запрос: если есть такой логин в таблице
             myCommand.Prepare();                                                                                                   //подготавливает строку
             myCommand.ExecuteNonQuery();                                                                                           //выполняет запрос
             LoginGlobal = (string)myCommand.ExecuteScalar();                                                                       //результат запроса
             if (LoginGlobal == login)
             {
                 myCommand.CommandText = string.Format("SELECT id FROM teacher WHERE login='******' AND password='******' ", login, pass); //запрос: если есть такой логин в таблице
                 myCommand.Prepare();                                                                                                //подготавливает строку
                 myCommand.ExecuteNonQuery();                                                                                        //выполняет запрос
                 IdTeacher = (int)myCommand.ExecuteScalar();                                                                         //результат запроса
                 MessageBox.Show("Вы зашли как преподаватель");
                 Teacher teacher = new Teacher();
                 teacher.Show();
                 this.Hide();
             }
             else
             {
                 MessageBox.Show("Логин или пароль не совпадают");
             }
         }
         myConnection.Close();
     }
     catch (Exception ex)
     {
     }
 }
示例#22
0
        public int GetStockCardEntryCount(MySql.Data.MySqlClient.MySqlCommand cmd)
        {
            string hql = "SELECT COUNT(*) FROM table_stockcardentry";

            cmd.CommandText = hql;
            int result = Convert.ToInt32(cmd.ExecuteScalar());

            return(result);
        }
示例#23
0
        public override void Update(IEntity en)
        {
            OpenConnection();
            MySql.Data.MySqlClient.MySqlTransaction trans    = m_connection.BeginTransaction();
            MySql.Data.MySqlClient.MySqlCommand     aCommand = new MySql.Data.MySqlClient.MySqlCommand();
            aCommand.Connection  = m_connection;
            aCommand.Transaction = trans;
            try
            {
                User e = (User)en;
                aCommand.CommandText = e.GetUpdateSQL();
                aCommand.ExecuteNonQuery();

                foreach (string kys in e.FORM_ACCESS_LIST.Keys)
                {
                    if (e.FORM_ACCESS_LIST[kys].ID > 0)
                    {
                        aCommand.CommandText = e.FORM_ACCESS_LIST[kys].GetUpdateSQL();
                        aCommand.ExecuteNonQuery();
                    }
                    else
                    {
                        aCommand.CommandText = e.FORM_ACCESS_LIST[kys].GetInsertSQL();
                        aCommand.ExecuteNonQuery();
                        aCommand.CommandText       = e.FORM_ACCESS_LIST[kys].GetMaximumIDSQL();
                        e.FORM_ACCESS_LIST[kys].ID = Convert.ToInt32(aCommand.ExecuteScalar());
                    }
                }
                aCommand.CommandText = FormAccess.GetAllByUserSQL(e.ID);
                MySql.Data.MySqlClient.MySqlDataReader r = aCommand.ExecuteReader();
                IList luc = FormAccess.GetAllStatic(r);
                r.Close();
                foreach (FormAccess chk in luc)
                {
                    chk.UPDATED = e.FORM_ACCESS_LIST.Contains(new KeyValuePair <string, FormAccess>(chk.CODE, chk));
                }
                foreach (FormAccess chk in luc)
                {
                    if (!chk.UPDATED)
                    {
                        aCommand.CommandText = chk.GetDeleteSQL();
                        aCommand.ExecuteNonQuery();
                    }
                }
                trans.Commit();
            }
            catch (Exception x)
            {
                trans.Rollback();
                throw new Exception(getErrorMessage(x));
            }
            finally
            {
                m_connection.Close();
            }
        }
示例#24
0
        public void fetchCustomerID()
        {
            string sql = "SELECT LAST_INSERT_ID()";

            if (Database.isConnected())
            {
                var cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, Database.connection);
                id = int.Parse(cmd.ExecuteScalar().ToString());
            }
        }
示例#25
0
        /// <summary>
        /// Execute a SqlCommand that returns the first column of the first record against an existing database connection
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connection">an existing database connection</param>
        /// <param name="cmdType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="cmdText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            object val = cmd.ExecuteScalar();

            cmd.Parameters.Clear();
            return(val);
        }
示例#26
0
        private void login(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            Application.DoEvents();

            DataRowView view  = (DataRowView)usuarioBindingSource.Current;
            string      senha = view["senha"].ToString();

            if (senha.Equals(senhaTextBox.Text))
            {
                //verificar online usuario
                MySql.Data.MySqlClient.MySqlCommand mycomm = myconn.CreateCommand();
                mycomm.CommandText = "select count(1) from usuario " +
                                     "where nome=@nome and senha=@senha";
                mycomm.Parameters.AddWithValue("nome", nomeComboBox.Text);
                mycomm.Parameters.AddWithValue("senha", senhaTextBox.Text);

                try
                {
                    myconn.Open();
                    int i = Convert.ToInt32(mycomm.ExecuteScalar());
                    if (i > 0)
                    {
                        btEnviar.Enabled   = true;
                        panelLogin.Visible = false;
                        usuarioId          = (int)view["id"];
                    }
                }
                catch (Exception ex)
                {
                    Cursor.Current = Cursors.Default;
                    Application.DoEvents();
                    MessageBox.Show(ex.Message);
                    return;
                }
                finally
                {
                    myconn.Close();
                }
                Cursor.Current = Cursors.Default;
                Application.DoEvents();
            }
            else
            {
                Cursor.Current = Cursors.Default;
                Application.DoEvents();
                MessageBox.Show("Login falhou");
            }
        }
示例#27
0
        public void SaveNoTransaction(Event e, MySql.Data.MySqlClient.MySqlCommand command)
        {
            try
            {
                m_command = command;
                DateTime trDate     = DateTime.Today;
                string   codesample = AutoNumberSetupRepository.GetCodeSampleByDomainName(m_command, "OpeningStock");
                Event    codeDate   = FindLastCodeAndTransactionDate(codesample);
                string   lastCode   = codeDate == null ? string.Empty : codeDate.CODE;
                DateTime lastDate   = codeDate == null ? trDate : codeDate.TRANSACTION_DATE;
                int      trCount    = RecordCount();
                e.CODE = AutoNumberSetupRepository.GetAutoNumberByDomainName(m_command, "OpeningStock", e.CODE, lastCode, lastDate, trDate, trCount == 0);

                OpeningStock stk = (OpeningStock)e;
                m_command.CommandText = e.GetInsertSQL();
                m_command.ExecuteNonQuery();
                m_command.CommandText = OpeningStock.SelectMaxIDSQL();
                stk.ID = Convert.ToInt32(m_command.ExecuteScalar());
                foreach (OpeningStockItem item in stk.EVENT_ITEMS)
                {
                    m_command.CommandText = item.GetInsertSQL();
                    m_command.ExecuteNonQuery();
                    m_command.CommandText = OpeningStockItem.SelectMaxIDSQL();
                    item.ID = Convert.ToInt32(m_command.ExecuteScalar());
                }
            }
            catch (Exception x)
            {
                e.ID = 0;
                foreach (EventItem item in e.EVENT_ITEMS)
                {
                    item.ID = 0;
                }
                throw x;
            }
        }
示例#28
0
 public static void Save(MySql.Data.MySqlClient.MySqlCommand cmd, VendorBalanceEntry sce)
 {
     if (sce.ID == 0)
     {
         cmd.CommandText = sce.GetInsertSQL();
         cmd.ExecuteNonQuery();
         cmd.CommandText = VendorBalanceEntry.SelectMaxIDSQL();
         sce.ID          = Convert.ToInt32(cmd.ExecuteScalar());
     }
     else
     {
         cmd.CommandText = sce.GetUpdateSQL();
         cmd.ExecuteNonQuery();
     }
 }
示例#29
0
        private void button3_Click(object sender, EventArgs e)
        {
            WriteLog("Count Players Online", Color.Gray);
            string connectionString;

            connectionString = "Data Source=" + databaseHost + ";User Id=" + databaseUser + ";Password="******";Database=" + realmDatabase;
            MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connectionString);
            conn.Open();
            string query = "SELECT COUNT(*)FROM account WHERE online=\"1\"";

            MySql.Data.MySqlClient.MySqlCommand resQuery = new MySql.Data.MySqlClient.MySqlCommand(query, conn);
            oCount      = Convert.ToInt16(resQuery.ExecuteScalar());
            label1.Text = "Players Online: " + oCount;
            conn.Close();
        }
示例#30
0
 public Boolean LicenceAvailable(String CompanyName, Int32 AppIdentifier)
 {
     try
     {
         String Commande = "SELECT (licences.LICENCES_NB - COUNT(activation_keys.ACTIVATION_KEY)) AS LICENCE_FREE FROM licences INNER JOIN softwares ON licences.SOFTWARE_ID = softwares.ID INNER JOIN customers ON licences.CUSTOMER_ID = customers.ID LEFT OUTER JOIN activation_keys ON activation_keys.CUSTOMER_ID = customers.ID AND activation_keys.SOFTWARE_ID = softwares.ID WHERE softwares.identifier=" + AppIdentifier + " AND customers.nom='" + CompanyName + "'";
         Connexion.Open();
         MySql.Data.MySqlClient.MySqlCommand sqlCmd = new MySql.Data.MySqlClient.MySqlCommand(Commande, Connexion);
         Int32 FreeLicence = (Int32)sqlCmd.ExecuteScalar();
         return(FreeLicence > 0);
     }
     catch (MySql.Data.MySqlClient.MySqlException ex)
     {
         _lasterror = ex.Message;
         return(false);
     }
 }
示例#31
0
        /// <summary>
        /// 使用离线数据库连接器,无需使用Open方法,获取数据库当前时间
        /// </summary>
        public override DateTime GetDateTimeNow()
        {
            DateTime ret = DateTime.Now;

            using (MySql.Data.MySqlClient.MySqlConnection con = new MySql.Data.MySqlClient.MySqlConnection(this.ConnectionText))
            {
                using (MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand("select now()", con))
                {
                    con.Open();
                    ret = Convert.ToDateTime(cmd.ExecuteScalar());
                    con.Close();
                }
            }

            return(ret);
        }
示例#32
0
 private void button3_Click(object sender, EventArgs e)
 {
     WriteLog("Count Players Online", Color.Gray);
     string connectionString;
     connectionString = "Data Source=" + databaseHost + ";User Id=" + databaseUser + ";Password="******";Database="+realmDatabase;
     MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connectionString);
     conn.Open();
     string query = "SELECT COUNT(*)FROM account WHERE online=\"1\"";
     MySql.Data.MySqlClient.MySqlCommand resQuery = new MySql.Data.MySqlClient.MySqlCommand(query, conn);
     oCount = Convert.ToInt16(resQuery.ExecuteScalar());
     label1.Text = "Players Online: " + oCount;
     conn.Close();
 }