예제 #1
0
        //获得数据库数据
        private void GetUserData()
        {
            MySQLConnection DBConn = null;
            DBConn = new MySQLConnection(new MySQLConnectionString(Configuration.getDBIp(), "template", Configuration.getDBUsername(), Configuration.getDBPassword()).AsString);
            DBConn.Open();
            MySQLCommand setformat = new MySQLCommand("set names gb2312", DBConn);
            setformat.ExecuteNonQuery();
            setformat.Dispose();

            string type = MainWindow.wfmodel.WFModel_Type;
            string sql = "select name, description,type from template where type = '"+type+"'";
            MySQLDataAdapter mda = new MySQLDataAdapter(sql, DBConn);

            DataTable ds = new DataTable();
            mda.Fill(ds);

            DBConn.Close();
            foreach (DataRow dr in ds.Rows)
            {
                TemplateModel um = new TemplateModel();
                um.name = dr["name"].ToString();
                um.desc = dr["description"].ToString();
                um.type = dr["type"].ToString();
                models.Add(um);
            }
            view.Source = models;
            this.listView1.DataContext = view;
        }
예제 #2
0
 /// <summary>
 /// 执行一条计算查询结果语句,返回查询结果(object)。
 /// </summary>
 /// <param name="SQLString">计算查询结果语句</param>
 /// <returns>查询结果(object)</returns>
 public object ExecuteScalar(string SQLString)
 {
     using (MySQLConnection connection = new MySQLConnection(connectionString))
     {
         using (MySQLCommand cmd = new 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 (MySQLException e)
             {
                 connection.Close();
                 throw e;
             }
         }
     }
 }
예제 #3
0
        //获得数据库数据
        private void GetUserData()
        {
            MySQLConnection DBConn = null;
            DBConn = new MySQLConnection(new MySQLConnectionString(Configuration.getDBIp(), "workflow", Configuration.getDBUsername(), Configuration.getDBPassword()).AsString);
            DBConn.Open();
            MySQLCommand setformat = new MySQLCommand("set names gb2312", DBConn);
            setformat.ExecuteNonQuery();
            setformat.Dispose();


            string sql = "select distinct User_Dept from tb_user";
            MySQLDataAdapter mda = new MySQLDataAdapter(sql, DBConn);

            DataTable ds = new DataTable();
            mda.Fill(ds);

            DBConn.Close();
            foreach (DataRow dr in ds.Rows)
            {
                UserModel um = new UserModel();
              
                um.Department = dr["User_Dept"].ToString();
             
                models.Add(um);
            }
            view.Source = models;
            this.listView1.DataContext = view;
        }
예제 #4
0
        //获得数据库数据
        private void GetUserData()
        {
            MySQLConnection DBConn = null;
            string connectStr = new MySQLConnectionString(Configuration.getDBIp(), "workflow", Configuration.getDBUsername(), Configuration.getDBPassword()).AsString;
            //System.Windows.Forms.MessageBox.Show(connectStr);
            DBConn = new MySQLConnection(connectStr);
            DBConn.Open();
            MySQLCommand setformat = new MySQLCommand("set names gb2312", DBConn);
            setformat.ExecuteNonQuery();
            setformat.Dispose();


            string sql = "select User_Id,User_Name,User_Dept,User_Job,User_Mail,User_Cell from tb_user";
            MySQLDataAdapter mda = new MySQLDataAdapter(sql, DBConn);

            DataTable ds = new DataTable();
            mda.Fill(ds);

            DBConn.Close();
            foreach (DataRow dr in ds.Rows)
            {
                UserModel um = new UserModel();
                um.ID = dr["User_Id"].ToString();
                um.Name = dr["User_Name"].ToString();
                um.Department = dr["User_Dept"].ToString();
             
                um.Email = dr["User_Mail"].ToString();
                um.PersonPosition = dr["User_Job"].ToString();
                um.Telephone = dr["User_Cell"].ToString();

                models.Add(um);
            }
            view.Source = models;
            this.listView1.DataContext = view;
        }
예제 #5
0
 /// <summary>
 /// 得到连接对象
 /// </summary>
 /// <returns></returns>
 public void GetConn()
 {
     MySQLConnection conn = null;
     conn = new MySQLConnection(new MySQLConnectionString("svn.breadth.cn", "mez", "root", "breadth2009").AsString);
     conn.Open();
     MySQLCommand comn = new MySQLCommand("set names utf-8", conn);
     comn.ExecuteNonQuery();
 }
예제 #6
0
        //�ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡι��캯��
        public UserManager(string name)
            : base(name, 560, 300)
        {
            MySQLConnection obSql;
            string linkStr = new MySQLConnectionString("localhost", "flox", "root", "00", 3306).AsString;
            linkStr += ";Character Set=GBK";
            obSql = new MySQLConnection(linkStr);
            obSql.Open(); // ִ�в�ѯ���

            MessageBox.Show(linkStr, "���ӳɹ�");
            MySQLCommand obCommand = null;
            MySQLDataReader obReader = null;
            string str = "";
            try
            {
                obCommand = new MySQLCommand("select username from cdb_members", obSql);
                obReader = obCommand.ExecuteReaderEx();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "ִ�д���");
            }
            if (obReader != null)
            {
                try
                {
                    str += obReader.FieldCount.ToString() + "\r\n";
                    while (obReader.Read())
                    {
                        for (int i = 0; i < obReader.FieldCount; i++)
                        {
                            string inputStr = obReader.GetString(i);

                            #region //note
                            ///Encoding inputCode = Encoding.GetEncoding("GBK");
                            ///Encoding outCode = Encoding.Unicode;
                            ///byte[] bta = inputCode.GetBytes(inputStr);
                            ///byte[] bta2 = Encoding.Convert(inputCode, outCode, bta);
                            ///string outStr = outCode.GetString(bta2);
                            #endregion

                            str += inputStr;
                        }
                        str += "\r\n";
                    }
                }
                finally
                {
                    obReader.Close();
                    obCommand.Dispose();
                    obSql.Close();
                }
            }
            MessageBox.Show(str, "�û��б�");
        }
예제 #7
0
        override public IDbCommand CreateCommand()
        {
            MySQLConnection sc = InternalConnection as MySQLConnection;

            if (null == sc)
            {
                throw new InvalidOperationException("InvalidConnType00" + InternalConnection.GetType().FullName);
            }

            return(sc.CreateCommand());
        }
예제 #8
0
        //确认本次添加操作
        private void Confirm_Click(object sender, RoutedEventArgs e)
        {
            //得到新的添加项
            int     id;
            DataRow row;

            row = TemplateSelectTable.NewRow();
            DataRowView selectrow = ListBox2.SelectedItem as DataRowView;

            if (selectrow == null)
            {
                MessageBox.Show("请选择要添加的表单模板!");
                return;
            }
            id = Convert.ToInt32(selectrow["ID"].ToString());
            row["Template_Id"]   = id;
            row["Template_Name"] = selectrow["NAME"].ToString();
            foreach (DataRow dr in TemplateDataTable.Rows)
            {
                if (Convert.ToInt32(dr["ID"].ToString()) == id)
                {
                    row["Template_HtmlSource"]  = dr["HTMLSOURCE"].ToString();
                    row["Template_Description"] = dr["DESCRIPTION"].ToString();
                    break;
                }
            }
            TemplateSelectTable.Rows.Add(row);
            TemplateSelectTable.AcceptChanges();


            //将添加的表单模板信息填入数据库的tb_templateselectlist表中
            MySQLConnection DBConn = null;

            DBConn = new MySQLConnection(new MySQLConnectionString(Configuration.getDBIp(), "template", Configuration.getDBUsername(), Configuration.getDBPassword()).AsString);
            DBConn.Open();
            AddFlag = false;
            for (int i = 0; i < TemplateSelectTable.Rows.Count; i++)
            {
                string       sqlInsert    = "insert into tb_templateselectlist(Template_Id , Template_Name,Template_HtmlSource,Template_Description) values ('" + TemplateSelectTable.Rows[i]["Template_Id"] + "' , '" + TemplateSelectTable.Rows[i]["Template_Name"] + "' , '" + TemplateSelectTable.Rows[i]["Template_HtmlSource"] + "' , '" + TemplateSelectTable.Rows[i]["Template_Description"] + "')";
                MySQLCommand mySqlCommand = new MySQLCommand(sqlInsert, DBConn);
                try
                {
                    mySqlCommand.ExecuteNonQuery();
                    AddFlag = true;
                }
                catch (Exception ex)
                {
                    String message = ex.Message;
                    MessageBox.Show("添加表单模板数据失败!该表单模板数据已存在于表中。" + message);
                }
            }
            DBConn.Close();
            this.Close();
        }
        private Queue <CoupleArenaZhanBaoItemData> GetZhanBao(long unionCouple)
        {
            Queue <CoupleArenaZhanBaoItemData> result2;

            lock (this.Mutex)
            {
                Queue <CoupleArenaZhanBaoItemData> result = null;
                if (!this.CoupleZhanBaoDict.TryGetValue(unionCouple, out result))
                {
                    result = new Queue <CoupleArenaZhanBaoItemData>();
                    MySQLConnection conn = null;
                    try
                    {
                        string sql = string.Format("SELECT `to_man_zoneid`,`to_man_rname`,`to_wife_zoneid`,`to_wife_rname`,`is_win`,`get_jifen` FROM t_couple_arena_zhan_bao WHERE `union_couple`={0} ORDER BY `time` DESC LIMIT {1};", unionCouple, this.MaxZhanBaoNum);
                        GameDBManager.SystemServerSQLEvents.AddEvent(string.Format("+SQL: {0}", sql), EventLevels.Important);
                        conn = DBManager.getInstance().DBConns.PopDBConnection();
                        MySQLCommand    cmd    = new MySQLCommand(sql, conn);
                        MySQLDataReader reader = cmd.ExecuteReaderEx();
                        List <CoupleArenaZhanBaoItemData> tmpList = new List <CoupleArenaZhanBaoItemData>();
                        while (reader != null && reader.Read())
                        {
                            tmpList.Add(new CoupleArenaZhanBaoItemData
                            {
                                TargetManZoneId    = Convert.ToInt32(reader["to_man_zoneid"].ToString()),
                                TargetManRoleName  = reader["to_man_rname"].ToString(),
                                TargetWifeZoneId   = Convert.ToInt32(reader["to_wife_zoneid"].ToString()),
                                TargetWifeRoleName = reader["to_wife_rname"].ToString(),
                                IsWin    = (Convert.ToInt32(reader["is_win"].ToString()) > 0),
                                GetJiFen = Convert.ToInt32(reader["get_jifen"].ToString())
                            });
                        }
                        tmpList.Reverse();
                        foreach (CoupleArenaZhanBaoItemData item in tmpList)
                        {
                            result.Enqueue(item);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManager.WriteLog(LogTypes.Error, "CoupleArenaDbManager.GetZhanBao " + ex.Message, null, true);
                    }
                    finally
                    {
                        if (conn != null)
                        {
                            DBManager.getInstance().DBConns.PushDBConnection(conn);
                        }
                    }
                    this.CoupleZhanBaoDict[unionCouple] = result;
                }
                result2 = result;
            }
            return(result2);
        }
예제 #10
0
        public void ExecuteNonQuery()
        {
            using (var c = new MySQLConnection(ConnectionString))
            {
                c.Open();

                DropTableNumberTestType(c);

                CreateTableNumberTestType(c);
            }
        }
예제 #11
0
 public void OpenAndClose()
 {
     using (var c = new MySQLConnection(ConnectionString))
     {
         Assert.True(c.State == ConnectionState.Closed);
         c.Open();
         Assert.True(c.State == ConnectionState.Open);
         c.Close();
         Assert.True(c.State == ConnectionState.Closed);
     }
 }
예제 #12
0
        private void btnInsert_Click(object sender, EventArgs e)
        {
            cmds[0] = tbQuery1.Text;
            cmds[1] = tbQuery2.Text;

            if (rbMySQL.Checked == true)
            {
                MySQLConnection MySQLCon = new MySQLConnection();

                MySQLCon.MySQLServer = tbServidor.Text;
                MySQLCon.MySQLPort   = tbPort.Text;
                MySQLCon.MySQLUser   = tbUser.Text;
                MySQLCon.MySQLPass   = tbPass.Text;

                MySQLCon.TransacaoMySQL(cmds);
            }
            else if (rbMSSQL.Checked == true)
            {
                MSSQLConnection MSSQLCon = new MSSQLConnection();

                MSSQLCon.MSSQLServer = tbServidor.Text;
                MSSQLCon.MSSQLPort   = tbPort.Text;
                MSSQLCon.MSSQLUser   = tbUser.Text;
                MSSQLCon.MSSQLPass   = tbPass.Text;

                MSSQLCon.TransacaoMSSQL(cmds);
            }
            else if (rbPgSQL.Checked == true)
            {
                PgSQLConnection PgSQLCon = new PgSQLConnection();

                PgSQLCon.PgSQLServer = tbServidor.Text;
                PgSQLCon.PgSQLPort   = tbPort.Text;
                PgSQLCon.PgSQLUser   = tbUser.Text;
                PgSQLCon.PgSQLPass   = tbPass.Text;

                PgSQLCon.TransacaoPgSQL(cmds);
            }
            else if (rbFirebird.Checked == true)
            {
                FirebirdConnection FirebirdCon = new FirebirdConnection();

                FirebirdCon.FirebirdServer = tbServidor.Text;
                FirebirdCon.FirebirdPort   = tbPort.Text;
                FirebirdCon.FirebirdUser   = tbUser.Text;
                FirebirdCon.FirebirdPass   = tbPass.Text;

                FirebirdCon.TransacaoFirebird(cmds);
            }
            else
            {
                MessageBox.Show("ERRO");
            }
        }
예제 #13
0
 private void Open()
 {
     //连接
     conn = new MySQLConnection(connectionString.AsString);
     //打开
     conn.Open();
     //解决乱码
     Gbk();
     //输入命令
     cmd = new MySQLCommand(sqlString, conn);
 }
예제 #14
0
        public static void SelectBuyBoCai(int bocaiType, long DataPeriods, out List <BuyBoCai2SDB> dList, bool isNoSend)
        {
            MySQLConnection conn  = null;
            DBManager       dbMgr = DBManager.getInstance();

            dList = null;
            try
            {
                conn = dbMgr.DBConns.PopDBConnection();
                string sql;
                if (isNoSend)
                {
                    sql = string.Format("SELECT `rid`,`RoleName`,`ZoneID`,`UserID`,`ServerID`,`BuyNum`,`BuyValue`,`IsSend`,`IsWin`  FROM t_bocai_buy_history WHERE `BocaiType`={0} AND `DataPeriods`={1} AND `IsSend`={2};", bocaiType, DataPeriods, 0);
                }
                else
                {
                    sql = string.Format("SELECT `rid`,`RoleName`,`ZoneID`,`UserID`,`ServerID`,`BuyNum`,`BuyValue`,`IsSend`,`IsWin`  FROM t_bocai_buy_history WHERE `BocaiType`={0} AND `DataPeriods`={1};", bocaiType, DataPeriods);
                }
                MySQLCommand    cmd    = new MySQLCommand(sql, conn);
                MySQLDataReader reader = cmd.ExecuteReaderEx();
                dList = new List <BuyBoCai2SDB>();
                while (reader.Read())
                {
                    BuyBoCai2SDB Item = new BuyBoCai2SDB
                    {
                        m_RoleName  = reader["RoleName"].ToString(),
                        strUserID   = reader["UserID"].ToString(),
                        strBuyValue = reader["BuyValue"].ToString(),
                        m_RoleID    = Convert.ToInt32(reader["rid"].ToString()),
                        ZoneID      = Convert.ToInt32(reader["ZoneID"].ToString()),
                        ServerId    = Convert.ToInt32(reader["ServerID"].ToString()),
                        BuyNum      = Convert.ToInt32(reader["BuyNum"].ToString()),
                        IsSend      = (Convert.ToInt32(reader["IsSend"].ToString()) > 0),
                        IsWin       = (Convert.ToInt32(reader["IsWin"].ToString()) > 0),
                        BocaiType   = bocaiType,
                        DataPeriods = DataPeriods
                    };
                    dList.Add(Item);
                }
                GameDBManager.SystemServerSQLEvents.AddEvent(string.Format("+SQL: {0}", sql), EventLevels.Important);
                cmd.Dispose();
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypes.Exception, string.Format("[ljl]{0}", ex.ToString()), null, true);
            }
            finally
            {
                if (null != conn)
                {
                    dbMgr.DBConns.PushDBConnection(conn);
                }
            }
        }
예제 #15
0
        public static bool UpdateMerlinData(DBManager dbMgr, int nRoleID, string[] fields, int nStartIndex)
        {
            bool result;

            if (fields == null || fields.Length != 15 || nStartIndex >= fields.Length)
            {
                result = false;
            }
            else
            {
                bool            ret  = false;
                MySQLConnection conn = null;
                try
                {
                    conn = dbMgr.DBConns.PopDBConnection();
                    if (fields[6] != "*")
                    {
                        string endTime = new DateTime(Convert.ToInt64(fields[6]) * 10000L).ToString("yyyy-MM-dd HH:mm:ss");
                        fields[6] = endTime;
                    }
                    for (int i = 7; i <= 14; i++)
                    {
                        if (fields[i] != "*")
                        {
                            fields[i] = (Convert.ToDouble(fields[i]) * 100.0).ToString();
                        }
                    }
                    string cmdText = DBWriter.FormatUpdateSQL(nRoleID, fields, nStartIndex, MerlinDBOperate.t_fieldNames, "t_merlin_magic_book", MerlinDBOperate.t_fieldTypes, "roleID");
                    GameDBManager.SystemServerSQLEvents.AddEvent(string.Format("+SQL: {0}", cmdText), EventLevels.Important);
                    MySQLCommand cmd = new MySQLCommand(cmdText, conn);
                    try
                    {
                        cmd.ExecuteNonQuery();
                        ret = true;
                    }
                    catch (Exception)
                    {
                        LogManager.WriteLog(LogTypes.Error, string.Format("写入数据库失败: {0}", cmdText), null, true);
                    }
                    cmd.Dispose();
                    cmd = null;
                }
                finally
                {
                    if (null != conn)
                    {
                        dbMgr.DBConns.PushDBConnection(conn);
                    }
                }
                result = ret;
            }
            return(result);
        }
예제 #16
0
 //contructor de la clase: estable la conexion con el servidor mysql
 public MySqlConectar()
 {
     try
     {
         cnn = new MySQLConnection(new MySQLConnectionString("localhost", "prueba", "root", "").AsString);
     }
     catch (MySQLException e)
     {
         System.Console.WriteLine("Fallo de conectar");
         System.Console.WriteLine(e.Message.ToString());
     }
 }
예제 #17
0
 private void ButtonOK_Click(object sender, EventArgs e)
 {
     if (TextBox8.Text == "" || TextBox9.Text == "")
     {
         if (TextBox8.Text == "")
         {
             labelN1.Text = "输入不能为空";
         }
         else
         {
             labelN1.Text = "    ";
         }
         if (TextBox9.Text == "")
         {
             labelN2.Text = "输入不能为空";
         }
         else
         {
             labelN2.Text = "    ";
         }
     }
     else
     {
         int             flag          = 0;
         string          tempa         = TextBox8.Text;
         string          tempb         = TextBox9.Text;
         MySQLConnection SQLconnection = new MySQLConnection(new MySQLConnectionString
                                                                 ("localhost", "DormitoryManage", "root", "123456").AsString);
         string SQLstr1 = "SELECT * FROM student_info WHERE studentNumber = " + PublicValue.STUNUM;
         string SQLstr2 = "UPDATE student_info set studentPhone = '" + TextBox8.Text + "',studentPassword = '******'";
         SQLconnection.Open();
         MySQLCommand SQLcommand1 = new MySQLCommand("SET NAMES GB2312", SQLconnection);
         SQLcommand1.ExecuteNonQuery();   //执行设置字符集的语句
         MySQLCommand    SQLcommand2 = new MySQLCommand(SQLstr1, SQLconnection);
         MySQLDataReader SQLreader   = (MySQLDataReader)SQLcommand2.ExecuteReader();
         if (SQLreader.Read())
         {
             string oldtempa = SQLreader["studentPhone"].ToString();
             string oldtempb = SQLreader["studentPassword"].ToString();
             if (tempa != oldtempa || tempb != oldtempb)
             {
                 flag = 1;
             }
         }
         if (flag == 1)
         {
             MySQLCommand SQLcommand3 = new MySQLCommand(SQLstr2, SQLconnection);
             SQLcommand3.ExecuteNonQuery();
             SQLconnection.Close();
             MessageBox.Show("修改成功", "提示");
         }
     }
 }
 public MySQLRepository(MySqlConnection connectionString)
 {
     try
     {
         conn = MySQLConnection.MySqlConnectionApplication();
     }
     catch (Exception ex)
     {
         //Need to log write
         throw ex;
     }
 }
예제 #19
0
 public void PushDBConnection(MySQLConnection conn)
 {
     if (null != conn)
     {
         lock (this.DBConns)
         {
             this.ReleaseConn();
             this.DBConns.Enqueue(conn);
         }
         this.SemaphoreClients.Release();
     }
 }
예제 #20
0
        public static long OperateDatacount(string sql)
        {
            long num = 0;

            using (MySQLConnection connection = new MySQLConnection(source()))
            {
                connection.Open();
                num = DoSqlcount(connection, sql);
                connection.Close();
            }
            return(num);
        }
예제 #21
0
        public void SelectFunction()
        {
            using (var c = new MySQLConnection(ConnectionString))
            {
                c.Open();

                using (var cmd = new MySQLCommand("select now();", c))
                {
                    var time = cmd.ExecuteScalar();
                }
            }
        }
 public MySqlUnitOfWork()
 {
     try
     {
         context = MySQLConnection.MySqlConnectionApplication();
     }
     catch (Exception ex)
     {
         // Need to log write
         throw ex;
     }
 }
예제 #23
0
        public static MerlinGrowthSaveDBData QueryMerlinData(DBManager dbMgr, int nRoleID)
        {
            MySQLConnection        conn       = null;
            MerlinGrowthSaveDBData MerlinData = null;

            try
            {
                conn = dbMgr.DBConns.PopDBConnection();
                string cmdText = string.Format("SELECT roleID, (SELECT rname  FROM t_roles WHERE rid = roleID ) AS roleName, occupation, level, level_up_fail_num, starNum, starExp, luckyPoint, toTicks, addTime, activeFrozen, activePalsy, activeSpeedDown, activeBlow, unActiveFrozen, unActivePalsy, unActiveSpeedDown, unActiveBlow FROM t_merlin_magic_book WHERE roleID = {0}", nRoleID);
                GameDBManager.SystemServerSQLEvents.AddEvent(string.Format("+SQL: {0}", cmdText), EventLevels.Important);
                MySQLCommand cmd = new MySQLCommand(cmdText, conn);
                try
                {
                    MySQLDataReader reader = cmd.ExecuteReaderEx();
                    if (reader.Read())
                    {
                        MerlinData                  = new MerlinGrowthSaveDBData();
                        MerlinData._RoleID          = Global.SafeConvertToInt32(reader["roleID"].ToString(), 10);
                        MerlinData._Occupation      = Global.SafeConvertToInt32(reader["occupation"].ToString(), 10);
                        MerlinData._Level           = Global.SafeConvertToInt32(reader["level"].ToString(), 10);
                        MerlinData._LevelUpFailNum  = Global.SafeConvertToInt32(reader["level_up_fail_num"].ToString(), 10);
                        MerlinData._StarNum         = Global.SafeConvertToInt32(reader["starNum"].ToString(), 10);
                        MerlinData._StarExp         = Global.SafeConvertToInt32(reader["starExp"].ToString(), 10);
                        MerlinData._LuckyPoint      = Global.SafeConvertToInt32(reader["luckyPoint"].ToString(), 10);
                        MerlinData._ToTicks         = DataHelper.ConvertToTicks(reader["toTicks"].ToString());
                        MerlinData._AddTime         = DataHelper.ConvertToTicks(reader["addTime"].ToString());
                        MerlinData._ActiveAttr[0]   = (double)(Global.SafeConvertToInt32(reader["activeFrozen"].ToString(), 10) / 100);
                        MerlinData._ActiveAttr[1]   = (double)(Global.SafeConvertToInt32(reader["activePalsy"].ToString(), 10) / 100);
                        MerlinData._ActiveAttr[2]   = (double)(Global.SafeConvertToInt32(reader["activeSpeedDown"].ToString(), 10) / 100);
                        MerlinData._ActiveAttr[3]   = (double)(Global.SafeConvertToInt32(reader["activeBlow"].ToString(), 10) / 100);
                        MerlinData._UnActiveAttr[0] = (double)(Global.SafeConvertToInt32(reader["unActiveFrozen"].ToString(), 10) / 100);
                        MerlinData._UnActiveAttr[1] = (double)(Global.SafeConvertToInt32(reader["unActivePalsy"].ToString(), 10) / 100);
                        MerlinData._UnActiveAttr[2] = (double)(Global.SafeConvertToInt32(reader["unActiveSpeedDown"].ToString(), 10) / 100);
                        MerlinData._UnActiveAttr[3] = (double)(Global.SafeConvertToInt32(reader["unActiveBlow"].ToString(), 10) / 100);
                    }
                }
                catch (Exception)
                {
                    LogManager.WriteLog(LogTypes.Error, string.Format("查询数据库失败: {0}", cmdText), null, true);
                }
                cmd.Dispose();
                cmd = null;
            }
            finally
            {
                if (null != conn)
                {
                    dbMgr.DBConns.PushDBConnection(conn);
                }
            }
            return(MerlinData);
        }
예제 #24
0
        public MyDbConnection1(string connStr, string dbNames)
        {
            bool            success = false;
            MySQLConnection dbConn  = null;

            try
            {
                Dictionary <string, string> mapParams = new Dictionary <string, string>();
                string[] strParams = connStr.Split(new char[]
                {
                    ';'
                });
                foreach (string param in strParams)
                {
                    string[] map = param.Split(new char[]
                    {
                        '='
                    });
                    if (map.Length == 2)
                    {
                        map[0]            = map[0].Trim();
                        map[1]            = map[1].Trim();
                        mapParams[map[0]] = map[1];
                    }
                }
                this.ConnStr = new MySQLConnectionString(mapParams["host"], mapParams["database"], mapParams["user id"], mapParams["password"]);
                dbConn       = new MySQLConnection(this.ConnStr.AsString);
                dbConn.Open();
                if (!string.IsNullOrEmpty(dbNames))
                {
                    MySQLCommand cmd = new MySQLCommand(string.Format("SET names '{0}'", dbNames), dbConn);
                    cmd.ExecuteNonQuery();
                }
                this.DatabaseName = this.DbConn.Database;
                success           = true;
                this.DbConn       = dbConn;
            }
            catch (Exception ex)
            {
                LogManager.WriteExceptionUseCache(ex.ToString());
            }
            if (!success && null != dbConn)
            {
                try
                {
                    dbConn.Close();
                }
                catch
                {
                }
            }
        }
예제 #25
0
        static void Main(string[] args)
        {
            try
            {
                long   t1, t2, t3, t4, t5, t6;
                int    affectedRows;
                Class1 test = new Class1();

                MySQLConnection con = new MySQLConnection("Data Source=mysql;Location=localhost;User ID=root;Password=root");
                bool            usenew = true, useold = true;
                if (args != null && args.Length > 0)
                {
                    usenew = args[0] == "new";
                    useold = args[0] == "old";
                }

                test.CreateTable(con);
                test.Delete(con);
                //--------------------------------Direct statements-------------------
                if (useold)
                {
                    t1           = DateTime.Now.Ticks;
                    affectedRows = test.InsertTest(con, false);
                    t2           = DateTime.Now.Ticks;
                    PrintTimeDiff("Insert of " + affectedRows + " rows with DIRECT statement", t2 - t1);

                    affectedRows = test.TestSelect(con, false);
                    t5           = DateTime.Now.Ticks;
                    PrintTimeDiff("Select of " + affectedRows + " rows with DIRECT statement", t5 - t2);
                }

                //--------------------------------Prepared statements-------------------
                if (usenew)
                {
                    t3           = DateTime.Now.Ticks;
                    affectedRows = test.InsertTest(con, true);
                    t4           = DateTime.Now.Ticks;
                    PrintTimeDiff("Insert of " + affectedRows + " rows with PREPARED statement", t4 - t3);

                    affectedRows = test.TestSelect(con, true);
                    t6           = DateTime.Now.Ticks;
                    PrintTimeDiff("Select of " + affectedRows + " rows with PREPARED statement", t6 - t4);
                }
                Console.WriteLine("End of the Test, Enter to exit");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message + e.StackTrace);
                Console.ReadLine();
            }
        }
예제 #26
0
        /// <summary>
        /// 获取DataSet数据对象
        /// </summary>
        /// <param name="sqlstr">SQL语句</param>
        /// <returns></returns>
        public static DataSet GetData(string sqlstr)
        {
            string  cs      = cnnStr;//source();
            DataSet dataSet = new DataSet();

            using (MySQLConnection connection = new MySQLConnection(cs))
            {
                connection.Open();
                new MySQLDataAdapter(sqlstr, connection).Fill(dataSet);
                connection.Close();
            }
            return(dataSet);
        }
예제 #27
0
        //数据库写入
        public void MysqlWrite(string Query)
        {
            MySQLConnection conn = null;

            //MySQLCommand commn = new MySQLCommand("set names utf-8", conn);
            conn = new MySQLConnection(new MySQLConnectionString(DB_Address, DB_Database, DB_User, DB_Pass).AsString);
            //string query = "select * from video";
            MySQLCommand cmd = new MySQLCommand(Query, conn);

            conn.Open();
            cmd.ExecuteNonQuery();//执行数据库代码
            conn.Close();
        }
 public static void InitializeConnection(DataBaseType db)
 {
     if (db == DataBaseType.SQLServer)
     {
         SQLServerConnection SQLServer = new SQLServerConnection();
         Connection = SQLServer;
     }
     else if (db == DataBaseType.MySQL)
     {
         MySQLConnection mySQL = new MySQLConnection();
         Connection = mySQL;
     }
 }
예제 #29
0
 private static MySQLConnection Open()
 {
     try
     {
         conn = new MySQLConnection(new MySQLConnectionString("localhost", "test", "root", "root").AsString);
         conn.Open();
         return(conn);
     }
     catch (Exception ex)
     {
         System.Windows.Forms.MessageBox.Show("数据库访问出错:" + ex.Message);
         return(null);
     }
 }
예제 #30
0
        private void saveResult(RequestBean req, string ringState)
        {
            MySQLConnection conn = getConn();

            string sqlstr = "insert into ring_state set "
                            + "batch_id=" + req.batchId
                            + ",mobile='" + req.mobile
                            + "',status='" + ringState
                            + "',moden_port='" + req.portName
                            + "',time=now()";
            MySQLCommand comm = new MySQLCommand(sqlstr, conn);

            comm.ExecuteNonQuery();
        }
예제 #31
0
        public Main()
        {
            InitializeComponent();
            DBConn = new MySQLConnection(new MySQLConnectionString("140.134.208.84", "parkingsystem", "root", "FCUIECS", 3306).AsString); //連資料庫

            connect();
            request("alien" + (char)13);
            delaytime(200);
            request("password" + (char)13);
            tSB_Exit.Enabled    = false;
            tSB_search.Enabled  = false;
            TSMI_help.Enabled   = false;
            tabControl1.Enabled = false;
        }
예제 #32
0
        /// <summary>
        /// 从数据库中查询
        /// </summary>
        public bool Query(MySQLConnection conn, string userID)
        {
            LogManager.WriteLog(LogTypes.Info, string.Format("从数据库加载用户数据: {0}", userID));

            this.UserID = userID;

            MySQLSelectCommand cmd = new MySQLSelectCommand(conn, new string[] { "rid", "userid", "rname", "sex", "occupation", "level", "zoneid", "changelifecount" }, new string[] { "t_roles" }, new object[, ] {
                { "userid", "=", userID }, { "isdel", "=", 0 }
            }, null, null);

            if (cmd.Table.Rows.Count > 0)
            {
                for (int i = 0; i < cmd.Table.Rows.Count; i++)
                {
                    ListRoleIDs.Add(Convert.ToInt32(cmd.Table.Rows[i]["rid"].ToString()));
                    ListRoleNames.Add(cmd.Table.Rows[i]["rname"].ToString());
                    ListRoleSexes.Add(Convert.ToInt32(cmd.Table.Rows[i]["sex"].ToString()));
                    ListRoleOccups.Add(Convert.ToInt32(cmd.Table.Rows[i]["occupation"].ToString()));
                    ListRoleLevels.Add(Convert.ToInt32(cmd.Table.Rows[i]["level"].ToString()));
                    ListRoleZoneIDs.Add(Convert.ToInt32(cmd.Table.Rows[i]["zoneid"].ToString()));
                    ListRoleChangeLifeCount.Add(Convert.ToInt32(cmd.Table.Rows[i]["changelifecount"].ToString()));
                }
            }

            this.Money = 0; //不充值的情况下,无记录
            cmd        = new MySQLSelectCommand(conn, new string[] { "money", "realmoney", "giftid", "giftjifen" }, new string[] { "t_money" }, new object[, ] {
                { "userid", "=", userID }
            }, null, null);
            if (cmd.Table.Rows.Count > 0)
            {
                this.Money     = Convert.ToInt32(cmd.Table.Rows[0]["money"].ToString());
                this.RealMoney = Convert.ToInt32(cmd.Table.Rows[0]["realmoney"].ToString());
                this.GiftID    = Convert.ToInt32(cmd.Table.Rows[0]["giftid"].ToString());
                this.GiftJiFen = Convert.ToInt32(cmd.Table.Rows[0]["giftjifen"].ToString());
            }

            // 推送信息 [4/23/2014 LiaoWei]
            cmd = new MySQLSelectCommand(conn,
                                         new string[] { "userid", "pushid", "lastlogintime" },
                                         new string[] { "t_pushmessageinfo" }, new object[, ] {
                { "userid", "=", userID }
            }, null, null);

            if (cmd.Table.Rows.Count > 0)
            {
                this.PushMessageID = cmd.Table.Rows[0]["pushid"].ToString();
            }

            return(true);
        }
예제 #33
0
        public Form_Main()
        {
            InitializeComponent();

            //this.Load += new EventHandler(Form_Main_Load);

            DBConn = new MySQLConnection(new MySQLConnectionString("140.134.208.84", "RFID_Project", "root", "FCUIECS", 3306).AsString); //連資料庫

            /*置入偵測體溫使用者控制項*/
            UserControl_Monitor monitor = new UserControl_Monitor();

            panel1.Controls.Clear();
            panel1.Controls.Add(monitor);
        }
        public bool editCompany(Base_Companys bs_cpn)
        {
            MySqlConnection con = MySQLConnection.connectionMySQL();

            try
            {
                con.Open();
                MySqlCommand cmd = new MySqlCommand("u_base_companys", con);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@i_Company_id", bs_cpn.Company_id);
                cmd.Parameters.AddWithValue("@i_Company_code", bs_cpn.Company_code);
                cmd.Parameters.AddWithValue("@i_Company_N_name", bs_cpn.Company_N_name);
                cmd.Parameters.AddWithValue("@i_Company_F_name", bs_cpn.Company_F_name);
                cmd.Parameters.AddWithValue("@i_Company_tax_id", bs_cpn.Company_tax_id);
                cmd.Parameters.AddWithValue("@i_Company_tax_subcode", bs_cpn.Company_tax_subcode);
                cmd.Parameters.AddWithValue("@i_Company_address_no", bs_cpn.Company_address_no);
                cmd.Parameters.AddWithValue("@i_Company_vilage", bs_cpn.Company_vilage);
                cmd.Parameters.AddWithValue("@i_Company_vilage_no", bs_cpn.Company_vilage_no);
                cmd.Parameters.AddWithValue("@i_Company_alley", bs_cpn.Company_alley);
                cmd.Parameters.AddWithValue("@i_Company_road", bs_cpn.Company_road);
                cmd.Parameters.AddWithValue("@i_Company_subdistrict", bs_cpn.Company_subdistrict);
                cmd.Parameters.AddWithValue("@i_Company_district", bs_cpn.Company_district);
                cmd.Parameters.AddWithValue("@i_Company_province", bs_cpn.Company_province);
                cmd.Parameters.AddWithValue("@i_Company_country", bs_cpn.Company_country);
                cmd.Parameters.AddWithValue("@i_Company_zipcode", bs_cpn.Company_zipcode);
                cmd.Parameters.AddWithValue("@i_Company_tel", bs_cpn.Company_tel);

                cmd.ExecuteNonQuery();

                return(true);
            }
            catch (MySqlException ex)
            {
                error = "MysqlException ==> Managers_Base --> Base_Companys_Manager --> editCompany() ";
                Log_Error._writeErrorFile(error, ex);
                return(false);
            }
            catch (Exception ex)
            {
                error = "Exception ==> Managers_Base --> Base_Companys_Manager --> editCompany() ";
                Log_Error._writeErrorFile(error, ex);
                return(false);
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
        }
예제 #35
0
        protected List <T> queryForList(string sql)
        {
            MySQLConnection conn = null;
            List <T>        list = null;

            try
            {
                conn = this.dbMgr.DBConns.PopDBConnection();
                MySQLCommand    cmd       = new MySQLCommand(sql, conn);
                MySQLDataReader reader    = cmd.ExecuteReaderEx();
                int             columnNum = reader.FieldCount;
                string[]        nameArray = new string[columnNum];
                while (reader.Read())
                {
                    int index = 0;
                    T   obj   = Activator.CreateInstance <T>();
                    for (int i = 0; i < columnNum; i++)
                    {
                        int _index = index++;
                        if (null == nameArray[_index])
                        {
                            nameArray[_index] = reader.GetName(_index);
                        }
                        string columnName  = nameArray[_index];
                        object columnValue = reader.GetValue(_index);
                        if (null == list)
                        {
                            list = new List <T>();
                        }
                        this.setValue(obj, columnName, columnValue);
                    }
                    list.Add(obj);
                }
                GameDBManager.SystemServerSQLEvents.AddEvent(string.Format("+SQL: {0}", sql), EventLevels.Important);
                cmd.Dispose();
            }
            catch (Exception e)
            {
                LogManager.WriteLog(LogTypes.Error, string.Format("查询数据库失败: {0},exception:{1}", sql, e), null, true);
                return(null);
            }
            finally
            {
                if (null != conn)
                {
                    this.dbMgr.DBConns.PushDBConnection(conn);
                }
            }
            return(list);
        }
예제 #36
0
        public int InsertTest(MySQLConnection con, bool useNew)
        {
            try
            {
                con.Open();

                MySQLCommand cmd;
                if (useNew)
                {
                    cmd = new MySQLCommand("INSERT INTO `test_table` (col1, col2, col3, col4) values (?,?,?,?)", con);                    //, `SerialNumberLastUsed`
                    cmd.UsePreparedStatement = true;
                    cmd.ServerCursor         = false;
                    cmd.Prepare();
                }
                else
                {
                    cmd = new MySQLCommand("INSERT INTO `test_table`(col1, col2, col3, col4) values (@col1, @col2, @col3, @col4)", con);                    //, `SerialNumberLastUsed`
                }

                MySQLParameter p1 = new MySQLParameter("@col1", DbType.Int32);
                cmd.Parameters.Add(p1);
                MySQLParameter p2 = new MySQLParameter("@col2", DbType.String);
                cmd.Parameters.Add(p2);
                MySQLParameter p3 = new MySQLParameter("@col1", DbType.Int16);
                cmd.Parameters.Add(p3);
                MySQLParameter p4 = new MySQLParameter("@col4", DbType.DateTime);
                cmd.Parameters.Add(p4);
                int affectedrows = 0;
                for (int i = 0; i < count; i++)
                {
                    p4.Value      = DateTime.Now;
                    p1.Value      = i;
                    p2.Value      = "Registro número " + i;
                    p2.Size       = p2.Value.ToString().Length;
                    p3.Value      = i * 10;
                    affectedrows += cmd.ExecuteNonQuery();
                }
                cmd.Dispose();
                con.Close();
                return(affectedrows);
            }
            catch (Exception e)
            {
                if (con != null)
                {
                    con.Close();
                }
                throw e;
            }
        }
예제 #37
0
파일: MySQL.cs 프로젝트: Ravenwolfe/Core
		public static bool CanConnect(MySQLConnection c, bool message = true)
		{
			if (c == null)
			{
				if (message)
				{
					CSOptions.ToConsole("Connection invalid: The connection no longer exists.");
				}

				return false;
			}

			if (c.HasError)
			{
				if (message)
				{
					CSOptions.ToConsole("Connection invalid: The connection has errors.");
				}

				return false;
			}

			if (c.Credentials == null || !c.Credentials.IsValid())
			{
				if (message)
				{
					CSOptions.ToConsole("Connection invalid: The connection credentials are invalid.");
				}

				return false;
			}

			if (Connections.Count >= CSOptions.MaxConnections)
			{
				if (message)
				{
					CSOptions.ToConsole("Connection invalid: Max connection limit ({0:#,0}) reached.", CSOptions.MaxConnections);
				}

				return false;
			}

			if (message)
			{
				CSOptions.ToConsole("Connection validated.");
			}

			return true;
		}
예제 #38
0
		public static void ExportMySQL()
		{
			if (!CMOptions.ModuleEnabled || !CMOptions.MySQLEnabled || !CMOptions.MySQLInfo.IsValid())
			{
				if (_Connection != null)
				{
					_Connection.Dispose();
					_Connection = null;
				}

				return;
			}

			if (_Connection != null && !_Connection.IsDisposed)
			{
				return;
			}

			CMOptions.ToConsole("Updating MySQL database...");
			
			VitaNexCore.TryCatch(
				() =>
				{
					_Connection = new MySQLConnection(CMOptions.MySQLInfo);
					_Connection.ConnectAsync(0, true,() =>
					{
						var a = new Action(UpdateMySQL);

						a.BeginInvoke(
							r =>
							{
								a.EndInvoke(r);
								UpdateMySQL();
							},
							null);
					});
				},
				x =>
				{
					if (_Connection != null)
					{
						_Connection.Dispose();
						_Connection = null;
					}

					CMOptions.ToConsole(x);
				});
		}
예제 #39
0
 public LoadIntoDatabase(string filepath, int type)
 {
     switch (type)
     {
         case 1:
             xmlparse = new MeiTuanXml(filepath);
             break;
         case 2:
             break;
         default:
             break;
     }
     staContext = new Statistic();
     conn = new MySQLConnection(new MySQLConnectionString("localhost", "gyzdatabase", "root", "9917622q").AsString);
     conn.Open();
 }
예제 #40
0
 public LoadIntoDatabase(string filepath, string host, string database, string user, string passwd, int type)
 {
     switch (type)
     {
         case 1:
             xmlparse = new MeiTuanXml(filepath);
             break;
         case 2:
             break;
         default:
             break;
     }
     staContext = new Statistic();
     conn = new MySQLConnection(new MySQLConnectionString(host, database, user, passwd).AsString);
     conn.Open();
 }
예제 #41
0
        //获得数据库数据
        void GetTemplateData()
        {
            models.Clear();
            MySQLConnection DBConn = null;
            DBConn = new MySQLConnection(new MySQLConnectionString(Configuration.getDBIp(), "workflow", Configuration.getDBUsername(), Configuration.getDBPassword()).AsString);
            try
            {

                DBConn.Open();
                MySQLCommand setformat = new MySQLCommand("set names gb2312", DBConn);
                setformat.ExecuteNonQuery();
                setformat.Dispose();


                string sql = "select model_name,owner,model_content,lastedit_time,model_disc,create_time from wf_model";
                MySQLDataAdapter mda = new MySQLDataAdapter(sql, DBConn);

                DataTable ds = new DataTable();
                mda.Fill(ds);

                DBConn.Close();
                foreach (DataRow dr in ds.Rows)
                {
                    WFModel wfm = new WFModel();
                    wfm.WFModel_CreateTime = dr["create_time"].ToString();
                    wfm.WFModel_LasteditTime = dr["lastedit_time"].ToString();
                    wfm.WFModel_Name = dr["model_name"].ToString();
                    wfm.WFModel_Owner = dr["owner"].ToString();
                    string test = dr["model_content"].ToString();
                    if (dr["model_content"] == null || dr["model_content"].ToString().Length<=0)
                    {
                        wfm.WFModel_Content = "";
                    }else
                        wfm.WFModel_Content = Encoding.Default.GetString((Byte[])dr["model_content"]);

                    models.Add(wfm);
                }
                view.Source = models;
                this.listView1.DataContext = view;
            }
            catch (Exception e)
            {
                MessageBox.Show("数据库连接失败,请检查网络连接或者数据库配置");
                return;
            }

        }
예제 #42
0
        //获得数据库数据
        DataTable GeteData()
        {
            MySQLConnection DBConn = null;
            DBConn = new MySQLConnection(new MySQLConnectionString(Configuration.getDBIp(), "template", Configuration.getDBUsername(), Configuration.getDBPassword()).AsString);
            DBConn.Open();
            //MySQLCommand DBCmd = new MySQLCommand("set names gb2312", DBConn);
            // DBCmd.ExecuteNonQuery();

            string sql = "select * from template";
            MySQLDataAdapter mda = new MySQLDataAdapter(sql, DBConn);

            DataTable ds = new DataTable();
            mda.Fill(ds);

            DBConn.Close();

            return ds;
        }
예제 #43
0
 //执行SQL语句,返回影响的记录数
 /// <summary>
 /// 执行SQL语句,返回影响的记录数
 /// </summary>
 /// <param name="SQLString">SQL语句</param>
 /// <returns>影响的记录数</returns>
 public int ExecuteNonQuery(string SQLString)
 {
     using (MySQLConnection connection = new MySQLConnection(connectionString))
     {
         using (MySQLCommand cmd = new MySQLCommand(SQLString, connection))
         {
             try
             {
                 connection.Open();
                 int rows = cmd.ExecuteNonQuery();
                 return rows;
             }
             catch (MySQLException e)
             {
                 connection.Close();
                 throw e;
             }
         }
     }
 }
예제 #44
0
 /// <summary>
 /// 执行SQL语句,返回影响的记录数
 /// </summary>
 /// <param name="SQLString">SQL语句</param>
 /// <returns>影响的记录数</returns>
 public int ExecuteNonQuery(string SQLString, params MySQLParameter[] cmdParms)
 {
     using (MySQLConnection connection = new MySQLConnection(connectionString))
     {
         using (MySQLCommand cmd = new MySQLCommand())
         {
             try
             {
                 PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                 int rows = cmd.ExecuteNonQuery();
                 cmd.Parameters.Clear();
                 return rows;
             }
             catch (MySQLException e)
             {
                 throw e;
             }
         }
     }
 }
예제 #45
0
        public static ToolboxCategoryItems loadTemplatebox()
        {
            MySQLConnection DBConn = new MySQLConnection(new MySQLConnectionString(Configuration.getDBIp(), "template", Configuration.getDBUsername(), Configuration.getDBPassword()).AsString);
            if (DBConn != null)
            {
                try
                {
                    DBConn.Open();
                    string sql = "select * from template";
                    MySQLDataAdapter mda = new MySQLDataAdapter(sql, DBConn);
                    MySQLCommand mcd = new MySQLCommand(sql, DBConn);
                    mcd.ExecuteNonQuery();
                    DataTable TemplateDataTable = new DataTable();
                    mda.Fill(TemplateDataTable);
                    DBConn.Close();
                    loadSystemIcon();

                    ToolboxCategoryItems toolboxCategoryItems = new ToolboxCategoryItems();
                    ToolboxCategory templates = new System.Activities.Presentation.Toolbox.ToolboxCategory("表单模板");

                    foreach (DataRow dr in TemplateDataTable.Rows)
                    {
                        ToolboxItemWrapper Template = new ToolboxItemWrapper(typeof(Wxwinter.BPM.WFDesigner.Template), dr["NAME"].ToString());
                        templates.Add(Template);
                    }
                    toolboxCategoryItems.Add(templates);
                    parentWindow.statusInfo.Text = "";
                    return toolboxCategoryItems;
                }
                catch (Exception e)
                {
                    parentWindow.statusInfo.Text = "数据库连接失败,请检查网络设置和数据库连接配置";
                    return null;
                }
                
            }
            else
            {
                return null;
            }
        }
 public static DataTable ExecuteDataTable(string SQLString)
 {
     using (MySQLConnection connection = new MySQLConnection(connectionString))
     {
         DataSet ds = new DataSet();
         try
         {
             connection.Open();
             MySQLDataAdapter command = new MySQLDataAdapter(SQLString, connection);
             MySQLCommand commn = new MySQLCommand("set names gbk", connection);
             commn.ExecuteNonQuery();
             command.Fill(ds, "ds");
             connection.Close();
         }
         catch (MySQLException ex)
         {
             throw new Exception(ex.Message);
         }
         return ds.Tables[0];
     }
 }
 public static DataTable ExecuteDataTable(string SQLString, params MySQLParameter[] cmdParms)
 {
     using (MySQLConnection connection = new MySQLConnection(connectionString))
     {
         MySQLCommand cmd = new MySQLCommand();
         PrepareCommand(cmd, connection, null, SQLString, cmdParms);
         using (MySQLDataAdapter da = new MySQLDataAdapter(cmd))
         {
             DataSet ds = new DataSet();
             try
             {
                 da.Fill(ds, "ds");
                 cmd.Parameters.Clear();
             }
             catch (MySQLException ex)
             {
                 throw new Exception(ex.Message);
             }
             return ds.Tables[0];
         }
     }
 }
예제 #48
0
        static void Main(string[] args)
        {
            try
            {
                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201406/20140609/mysql
                // "C:\util\xampp-win32-1.8.0-VC9\xampp\mysql_start.bat"
                // ex = {"Authentication to host '192.168.1.211' for user 'arvo' using method
                // 'mysql_native_password' failed with message: Reading from the stream has failed."}



                var uri = new Uri("mysql://*****:*****@192.168.1.211");

                // 192.168.1.211:3306 arvo xxx
                var myConnectionString = "server=127.0.0.1;database=test;uid=root;";
                //var myConnectionString = "server=192.168.1.211;database=test;uid=arvo;password=xxx;";
                // DbConnection
                var myConnection = new MySQLConnection(myConnectionString);
                string selectQuery = "show databases";
                // DbCommand
                var myCommand = new MySQLCommand(selectQuery);
                myCommand.Connection = myConnection;
                myConnection.Open();
                //var i = myCommand.ExecuteScalar();

                var a = new __DbDataAdapter { SelectCommand = myCommand };
                var t = new DataTable();
                //var ds = new DataSet();
                a.Fill(t);

                myCommand.Connection.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }
예제 #49
0
        public void GetPeopleDate(string str)
        {
            models.Clear();
            MySQLConnection DBConn = null;
            DBConn = new MySQLConnection(new MySQLConnectionString(Configuration.getDBIp(), "workflow", Configuration.getDBUsername(), Configuration.getDBPassword()).AsString);
            try
            {
                DBConn.Open();
                MySQLCommand setformat = new MySQLCommand("set names gb2312", DBConn);
                setformat.ExecuteNonQuery();
                setformat.Dispose();

                string sql = "select tb_per.User_Name , tb_user.User_Mail from tb_user, tb_per where tb_per.user_name = tb_user.User_Name and tb_per.user_authority = ";
                sql += "'" + str + "'";
                //MessageBox.Show(sql);
                MySQLDataAdapter mda = new MySQLDataAdapter(sql, DBConn);

                DataTable ds = new DataTable();
                mda.Fill(ds);
                DBConn.Close();

                foreach (DataRow dr in ds.Rows)
                {
                    peopleInfo wfm = new peopleInfo();
                    wfm.peopleName = dr["user_name"].ToString();
                    wfm.peopleEmail = dr["User_Mail"].ToString();       
                    models.Add(wfm);
                }
                view.Source = models;
                this.peopleListView.DataContext = view;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("数据库连接失败,请检查网络连接或者数据库配置");
                return;
            }
        }
예제 #50
0
        public DatabaseHelper(string database, string user, string pwd)
        {
            try
            {
                this.databaseName = database;
                this.username = user;
                this.password = pwd;

                logStringBuilder = new StringBuilder();
                logStringBuilder.Append("New slq connection: database Name is ");
                logStringBuilder.Append(databaseName);
                logStringBuilder.Append(", user name is ");
                logStringBuilder.Append(username);
                logStringBuilder.Append(", password is ");
                logStringBuilder.Append(password);
                Common.Log(logStringBuilder.ToString());
                conn = new MySQLConnection(new MySQLConnectionString(databaseName, username, password).AsString);
            }
            catch (Exception ex)
            {
                Common.Log(ex.ToString());
            }
        }
        public static MySQLDataReader ExecuteReader(string SQLString, params MySQLParameter[] cmdParms)
        {
            MySQLConnection connection = new MySQLConnection(connectionString);
            MySQLCommand cmd = new MySQLCommand();
            MySQLDataReader myReader = null;
            try
            {
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                myReader = cmd.ExecuteReaderEx();
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (MySQLException e)
            {
                throw e;
            }
            finally
            {
                myReader.Close();
                cmd.Dispose();
                connection.Close();

            }
        }
        // X:\jsc.svn\examples\java\hybrid\Test\TestJVMCLRAsync\TestJVMCLRAsync\Program.cs
        // can we send in the caller IButtonProxy ?
        // as long the interface is async, one way we could do it.
        // if it allows a continuation we would have
        // to reinit our state
        // this would be possible only if we encrypt and sign
        // our state
        // as we cannot trust the other device to not change our expected state

        static ApplicationWebService()
        {
            // X:\jsc.svn\examples\javascript\LINQ\test\auto\TestSelect\TestAppEngineOrderByThenGroupBy\ApplicationWebService.cs
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201409/20140908

            // jsc should not try to do cctor on client side
            // X:\jsc.svn\examples\javascript\Test\TestWebServiceStaticConstructor\TestWebServiceStaticConstructor\ApplicationWebService.cs



            #region MySQLConnection

            // X:\jsc.svn\examples\javascript\LINQ\test\TestSelectGroupByAndConstant\TestSelectGroupByAndConstant\ApplicationWebService.cs

            // the safe way to hint we need to talk PHP dialect
            QueryExpressionBuilder.Dialect = QueryExpressionBuilderDialect.MySQL;
            QueryExpressionBuilder.WithConnection =
                y =>
            {
                Console.WriteLine("enter WithConnection");

                //var DataSource = "file:xApplicationPerformance.xlsx.sqlite";
                var cc0 = new MySQLConnection(

                    new System.Data.MySQL.MySQLConnectionStringBuilder
                {
                    //Database = 

                    UserID = "root",
                    Server = "127.0.0.1",

                    //SslMode = MySQLSslMode.VerifyFull

                    //ConnectionTimeout = 3000

                }.ToString()
                //new MySQLConnectionStringBuilder { DataSource = "file:PerformanceResourceTimingData2.xlsx.sqlite" }.ToString()
                );





                // Additional information: Authentication to host '' for user '' using method 'mysql_native_password' failed with message: Access denied for user ''@'asus7' (using password: NO)
                // Additional information: Unable to connect to any of the specified MySQL hosts.
                cc0.Open();

                #region use db
                {
                    //var a = Assembly.GetExecutingAssembly().GetName();


                    // SkipUntilIfAny ???
                    //var QDataSource = a.Name + ":" + DataSource.SkipUntilIfAny("file:").TakeUntilIfAny(".xlsx.sqlite");
                    var QDataSource = "TestAppEngineOrderByThenGroupBy";

                    // QDataSource.Length = 76
                    var QLengthb = QDataSource.Length;

                    // Database	64
                    cc0.CreateCommand("CREATE DATABASE IF NOT EXISTS `" + QDataSource + "`").ExecuteScalar();
                    cc0.CreateCommand("use `" + QDataSource + "`").ExecuteScalar();
                }
                #endregion

                y(cc0);


                // jsc java does the wrong thing here
                cc0.Close();
                //cc0.Dispose();
                Console.WriteLine("exit WithConnection");
            };
            #endregion
        }
예제 #53
0
		private static void UpdateMySQL()
		{
			if (!CMOptions.ModuleEnabled || !CMOptions.MySQLEnabled || !CMOptions.MySQLInfo.IsValid())
			{
				if (_Connection != null)
				{
					_Connection.Dispose();
					_Connection = null;
				}

				return;
			}

			if (_Connection == null || _Connection.IsDisposed)
			{
				_Connection = null;
				return;
			}

			if (!_Connection.Connected)
			{
				_Connection.Dispose();
				_Connection = null;
				return;
			}

			using (_Connection)
			{
				#region Conquests
				CMOptions.ToConsole("Exporting conquests...");

				Conquest[] cList = ConquestRegistry.Values.Where(c => c != null && !c.Deleted).ToArray();

				_Connection.NonQuery(GetCreateQuery("conquests"));
				_Connection.Truncate("conquests");

				int cCount = 0;

				foreach (Conquest c in cList)
				{
					var sData = new MySQLData("id_con", c.UID.Value);

					using (var props = new PropertyList<Conquest>(c))
					{
						props.RemoveKeyRange("UID", "");

						int pc =
							props.Count(
								kv =>
								{
									CMOptions.ToConsole("Prop: {0} = {1}", kv.Key, kv.Value);
									
									return _Connection.Insert("conquests", new[] {sData, new MySQLData("key", kv.Key), new MySQLData("val", kv.Value)});
								});

						if (pc == props.Count)
						{
							++cCount;
						}
					}
				}

				CMOptions.ToConsole("Exported {0:#,0} conquests.", cCount);
				#endregion

				#region Profiles
				CMOptions.ToConsole("Exporting profiles...");

				ConquestProfile[] pList = Profiles.Values.Where(p => p != null && p.Owner != null).ToArray();

				_Connection.NonQuery(GetCreateQuery("profiles"));
				_Connection.Truncate("profiles");

				int pCount =
					pList.Count(
						p =>
						_Connection.Insert(
							"profiles",
							new[]
							{
								new MySQLData("id_owner", p.Owner.Serial.Value), new MySQLData("owner", p.Owner.RawName),
								new MySQLData("points", p.GetPointsTotal()), new MySQLData("credit", p.Credit)
							}));

				CMOptions.ToConsole("Exported {0:#,0} profiles.", pCount);
				#endregion

				#region States
				CMOptions.ToConsole("Exporting states...");

				_Connection.NonQuery(GetCreateQuery("states"));
				_Connection.Truncate("states");

				int sCount = 0;

				foreach (var p in pList)
				{
					foreach (var s in p)
					{
						var sData = new MySQLData("id_state", s.UID.Value);
						var cData = new MySQLData("id_con", s.Conquest.UID.Value);
						var oData = new MySQLData("id_owner", s.Owner.Serial.Value);

						using (var props = new PropertyList<ConquestState>(s))
						{
							props.Remove("UID");
							props.Remove("Conquest");
							props.Remove("Owner");
							props.Remove("ConquestExists");

							int pc =
								props.Count(
									kv =>
									_Connection.Insert(
										"states", new[] {sData, cData, oData, new MySQLData("key", kv.Key), new MySQLData("val", kv.Value)}));

							if (pc == props.Count)
							{
								++sCount;
							}
						}
					}
				}

				CMOptions.ToConsole("Exported {0:#,0} states.", sCount);
				#endregion
			}

			_Connection = null;
		}
 //获取起始页码和结束页码
 public static DataTable ExecuteDataTable(string cmdText, int startResord, int maxRecord)
 {
     using (MySQLConnection connection = new MySQLConnection(connectionString))
     {
         DataSet ds = new DataSet();
         try
         {
             connection.Open();
             MySQLDataAdapter command = new MySQLDataAdapter(cmdText, connection);
             command.Fill(ds, startResord, maxRecord, "ds");
             connection.Close();
         }
         catch (MySQLException ex)
         {
             throw new Exception(ex.Message);
         }
         return ds.Tables[0];
     }
 }
예제 #55
0
    static void Main(string[] args)
    {
        #region MySQLConnection

        // X:\jsc.svn\examples\javascript\LINQ\test\TestSelectGroupByAndConstant\TestSelectGroupByAndConstant\ApplicationWebService.cs

        // the idea is to test MySQL as we have LINQ to SQL also running in chrome now
        //var mysqld = @"C:\util\xampp-win32-1.8.0-VC9\xampp\mysql\bin\mysqld.exe";
        //// --standalone --console

        //var mysqldp = Process.Start(mysqld, " --standalone --console");

        // Additional information: WaitForInputIdle failed.  This could be because the process does not have a graphical interface.
        //mysqldp.WaitForInputIdle();
        Thread.Sleep(3000);

        // the safe way to hint we need to talk PHP dialect
        QueryExpressionBuilder.Dialect = QueryExpressionBuilderDialect.MySQL;
        QueryExpressionBuilder.WithConnection =
            y =>
            {
                var DataSource = "file:xApplicationPerformance.xlsx.sqlite";
                var cc0 = new MySQLConnection(

                    new System.Data.MySQL.MySQLConnectionStringBuilder
                {


                    UserID = "tssl",
                    Server = "192.168.1.211",
                    // password is useless if client cert is to be used
                    Password = "******",
                    SslMode = MySQLSslMode.Required,

                    // private key
                    CertificateFile = @"X:\Monese\network\certs\local_devsql1\local_sql_client.pfx",
                    //ConnectionTimeout = 3000

                }.ToString()
                //new MySQLConnectionStringBuilder { DataSource = "file:PerformanceResourceTimingData2.xlsx.sqlite" }.ToString()
                );





                // Additional information: Authentication to host '' for user '' using method 'mysql_native_password' failed with message: Access denied for user ''@'asus7' (using password: NO)
                // Additional information: Unable to connect to any of the specified MySQL hosts.
                cc0.Open();

                #region use db
                {
                    var a = Assembly.GetExecutingAssembly().GetName();


                    // SkipUntilIfAny ???
                    var QDataSource = a.Name + ":" + DataSource.SkipUntilIfAny("file:").TakeUntilIfAny(".xlsx.sqlite");

                    // QDataSource.Length = 76
                    var QLengthb = QDataSource.Length;

                    // Database	64
                    cc0.CreateCommand("CREATE DATABASE IF NOT EXISTS `" + QDataSource + "`").ExecuteScalar();
                    cc0.CreateCommand("use `" + QDataSource + "`").ExecuteScalar();
                }
                #endregion

                y(cc0);

                cc0.Dispose();
            };
        #endregion


        new PerformanceResourceTimingData2ApplicationPerformance().Delete();

        new PerformanceResourceTimingData2ApplicationPerformance().Insert(
            new PerformanceResourceTimingData2ApplicationPerformanceRow
        {
            connectEnd = 9,
            connectStart = 5,
            Tag = "first insert"
        },

            new PerformanceResourceTimingData2ApplicationPerformanceRow
        {
            connectStart = 5,
            connectEnd = 111,
            Tag = "middle insert"
        },

            new PerformanceResourceTimingData2ApplicationPerformanceRow
        {
            connectStart = 5,
            connectEnd = 11,
            Tag = "Last insert, selected by group by"
        }
        );


        // https://code.google.com/p/chromium/issues/detail?id=369239&can=5&colspec=ID%20Pri%20M%20Iteration%20ReleaseBlock%20Cr%20Status%20Owner%20Summary%20OS%20Modified

        var f = (
            from x in new PerformanceResourceTimingData2ApplicationPerformance()
                //orderby x.Key ascending
                // MYSQL and SQLITE seem to behave differently? in reverse actually!
            orderby x.connectEnd descending
            // { f = { c = 3, Tag = first insert } }

            //orderby x.Key ascending
            // { f = { c = 3, Tag = Last insert, selected by group by } }
            // { f = { c = 3, Tag = first insert } }
            group x by x.connectStart into gg
            select new
            {
                c = gg.Count(),
                // need orderby x.Key descending !
                gg.Last().Tag
            }

        ).FirstOrDefault();

        System.Console.WriteLine(
            new { f }
            );

        //mysqldp.CloseMainWindow();
        Debugger.Break();


    }
        //执行SQL语句,返回影响的记录数
        //<param name="sqlString">sql语句</param>
        public static int ExecuteNonQuery(string SQLString)
        {
            using (MySQLConnection connection = new MySQLConnection(connectionString))
            {

                using (MySQLCommand cmd = new MySQLCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        MySQLCommand setformat = new MySQLCommand("set names gb2312", connection);
                        setformat.ExecuteNonQuery();
                        setformat.Dispose();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (MySQLException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }
 private static void PrepareCommand(MySQLCommand cmd, MySQLConnection conn, MySQLTransaction trans, string cmdText, MySQLParameter[] cmdParms)
 {
     if (conn.State != ConnectionState.Open)
         conn.Open();
     cmd.Connection = conn;
     cmd.CommandText = cmdText;
     if (trans != null)
         cmd.Transaction = trans;
     cmd.CommandType = CommandType.Text;//cmdType;
     if (cmdParms != null)
     {
         foreach (MySQLParameter parameter in cmdParms)
         {
             if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
             (parameter.Value == null))
             {
                 parameter.Value = DBNull.Value;
             }
             cmd.Parameters.Add(parameter);
         }
     }
     conn.Close();
 }
        public static MySQLDataReader ExecuteReader(string strSQL)
        {
            MySQLConnection connection = new MySQLConnection(connectionString);
            MySQLCommand cmd = new MySQLCommand(strSQL, connection);
            MySQLDataReader myReader = null;
            try
            {
                connection.Open();
                MySQLDataAdapter command = new MySQLDataAdapter(strSQL, connection);
                MySQLCommand commn = new MySQLCommand("set names gbk", connection);
                myReader = cmd.ExecuteReaderEx();

                return myReader;
            }
            catch (MySQLException e)
            {
                throw e;
            }
            finally
            {
                myReader.Close();
            }
        }
 public static object ExecuteScalar(string SQLString, params MySQLParameter[] cmdParms)
 {
     using (MySQLConnection connection = new MySQLConnection(connectionString))
     {
         using (MySQLCommand cmd = new 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 (MySQLException e)
             {
                 throw e;
             }
         }
     }
 }
예제 #60
0
        static void Main(string[] args)
        {
            //   while (true)
            //    {

                try
                {
                    StreamReader objReader = new StreamReader("setting.ini");
                    string sLine = "";
                    ArrayList arrText = new ArrayList();
                    while (sLine != null)
                    {
                        sLine = objReader.ReadLine();
                        if (sLine != null)
                            arrText.Add(sLine);
                    }
                    objReader.Close();
                   // foreach (string sOutput in arrText)
                   // dbconn = sOutput;
                    //MySQLConnection conn = new MySQLConnection(new MySQLConnectionString("192.168.234.129", "qqnotic", "toryzen", "q1w2e3r4").AsString);//实例化一个连接对象其中myquest为数据库名,root为数据库用户名,amttgroup为数据库密码
                    MySQLConnection conn = new MySQLConnection(new MySQLConnectionString(arrText[0].ToString(), arrText[1].ToString(), arrText[2].ToString(), arrText[3].ToString()).AsString);//实例化一个连接对象其中myquest为数据库名,root为数据库用户名,amttgroup为数据库密码
                    conn.Open();
                    MySQLCommand commn = new MySQLCommand("set names gb2312;", conn);
                    commn.ExecuteNonQuery();
                    MySQLCommand cmds = new MySQLCommand("select * from qqnotic where isok = 0 limit 1", conn);
                    MySQLDataReader reader = cmds.ExecuteReaderEx();
                    while (reader.Read())
                    {
                        int userid = int.Parse(reader["userid"].ToString()); //用户id
                        int checktype = int.Parse(reader["btype"].ToString()); //业务类型

                        MySQLCommand cmdname = new MySQLCommand("select * from qqname where id = " + userid, conn);
                        MySQLDataReader readername = cmdname.ExecuteReaderEx();
                        while (readername.Read())
                        {
                            qq = int.Parse(readername["qqnum"].ToString()); //qq号码
                            qqname = (string)readername["qqname"];   //qq昵称
                            realname = (string)readername["realname"]; //用户真名
                        }

                        bbtype = "光宇信息中心通知";   //通知标题
                        bbcontent = (string)reader["content"];  //通知内容

                        /* 若指定通知类型 */
                        if (checktype != 0)
                        {

                            MySQLCommand cmdtype = new MySQLCommand("select * from btype where id = " + checktype, conn);
                            MySQLDataReader btype = cmdtype.ExecuteReaderEx();
                            while (btype.Read())
                            {
                                bbtype = (string)btype["type"]; //通知标题
                                bbcontent = (string)btype["content"]; //通知内容
                            }

                        }

                        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));

                        int timeStamp = (int)(System.DateTime.Now - startTime).TotalSeconds;

                        MySQLCommand excmds = new MySQLCommand("UPDATE `qqnotic`.`qqnotic` SET `isok` = '1',`extime` = " + timeStamp + " WHERE `qqnotic`.`id` =" + reader["id"], conn);

                        excmds.ExecuteNonQuery(); //写入系统时间

                        notis = bbtype + ":\n" + realname + "您好," + bbcontent;

                        Console.WriteLine(System.DateTime.Now + "向用户" + realname + "(" + qq + ") 发送一条信息!");
                    }
                    conn.Close();
                }
                catch { Exception e; }

                if (qq != 0 && notis != "")
                {
                    try
                    {
                        Clipboard.Clear();
                        Clipboard.SetDataObject(notis,true);
                    }
                    catch { Exception e; }
                    const int WM_CHAR = 0x0102;
                    const int WM_KEYDOWN = 0x0100;
                    const int WM_PASTE = 0x0302;
                    const int WM_SETTEXT = 0x000C;
                    const int WM_Close = 0x0010;
                    string[] cmd = new string[] { "start tencent://message/?uin=" + qq + "&Site=gyyx.cn&Menu=yes" };
                    Cmd(cmd);
                    Thread.Sleep(1000);
                    EnumWindows(PrintWindow, IntPtr.Zero);
                    string tr = notis;
                    IntPtr hwndCalc = hander;

                    //ShowWindow(hwndCalc,1);

                    PostMessage(hwndCalc, WM_PASTE, 0, 0);
                    Thread.Sleep(500);
                    PostMessage(hwndCalc, WM_KEYDOWN, 13, 0);
                    Thread.Sleep(500);
                    //PostMessage(hwndCalc, WM_KEYDOWN, 27, 0);
                    PostMessage(hwndCalc, WM_Close, 0, 0);
                    Thread.Sleep(1000);
                    qq = 0;
                    notis = "";
                }
             //   else { Thread.Sleep(6000); }

               //     }
        }