Ejemplo n.º 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;
        }
Ejemplo n.º 2
0
        private static void CreateTableNumberTestType(MySQLConnection c)
        {
            using (var cmd = new MySQLCommand(@"
CREATE TABLE number_type_test
(
id INT NOT NULL,
COL_TINYINT TINYINT ,
COL_U_TINYINT  TINYINT unsigned,

COL_SMALLINT SMALLINT ,
COL_MEDIUMINT  MEDIUMINT ,
COL_INT INT ,
COL_BIGINT BIGINT ,
COL_DECIMAL DECIMAL(18,6) ,
COL_FLOAT FLOAT ,
COL_DOUBLE DOUBLE ,

COL_U_SMALLINT SMALLINT UNSIGNED,
COL_U_MEDIUMINT  MEDIUMINT UNSIGNED,
COL_U_INT INT UNSIGNED,
COL_U_BIGINT  BIGINT UNSIGNED,
COL_U_DECIMAL  DECIMAL UNSIGNED,

COL_BIT BIT(2) ,
PRIMARY KEY (id));
", c))
            {
                cmd.ExecuteNonQuery();
            }
        }
Ejemplo n.º 3
0
 public int AccountRequest(string pwd)
 {
     try {
         con.Open();
         sql = "INSERT INTO users(user_password) VALUES(" + pwd + ")";
         MySQLCommand com = new MySQLCommand(sql, con);
         com.ExecuteNonQuery();
         sql = "SELECT LAST_INSERT_ID()";
         com = new MySQLCommand(sql, con);
         DbDataReader reader = com.ExecuteReader();
         int user_id = 0;
         if(reader.Read())
         {
             user_id = Int32.Parse(reader["user_id"].ToString());
         } 
         sql = "INSERT INTO users_information VALUES(null,null,null,null)";
         com = new MySQLCommand(sql, con);
         com.ExecuteNonQuery();
         return user_id;
     }
     catch { return 0; }
     finally
     {
         con.Close();
     }
 }
Ejemplo n.º 4
0
        public void ExecuteScalarForAnyFieldType(string mySqlTypeDeclaration, string insertedLiteral, object expectedValue)
        {
            var c = CachedConnection;

            using (var cmd1 = new MySQLCommand("DROP TABLE IF EXISTS number_type_test", c))
                cmd1.ExecuteNonQuery();

            using (var cmd2 = new MySQLCommand($@"CREATE TABLE number_type_test ( id INT NOT NULL,COL_VALUE {mySqlTypeDeclaration},PRIMARY KEY (id));", c))
                cmd2.ExecuteNonQuery();

            using (var cmd3 = new MySQLCommand($@"INSERT INTO number_type_test ( id ,COL_VALUE)values(0,{insertedLiteral});", c)) cmd3.ExecuteNonQuery();

            using (var cmd = new MySQLCommand("select COL_VALUE from number_type_test where id=0", c))
            {
                object executeScalar = cmd.ExecuteScalar();
                Assert.NotNull(executeScalar);
                if (expectedValue == null)
                {
                    Assert.Null(executeScalar);
                }
                else
                {
                    Assert.NotNull(executeScalar);
                    Assert.IsType(expectedValue.GetType(), executeScalar);
                    Assert.Equal(expectedValue, executeScalar);
                }
            }
        }
Ejemplo n.º 5
0
 public AccountInfo AccountInfoReader(int user_id)
 {
     try {
         con.Open();
         sql = "SELECT* FROM users_information WHERE user_id = " + user_id;
         MySQLCommand com = new MySQLCommand(sql, con);
         DbDataReader reader = com.ExecuteReader();
         if(reader.Read())
         {
             AccountInfo accountInfo = new AccountInfo();
             accountInfo.Sex = short.Parse(reader["user_sex"].ToString());
             accountInfo.Birthday = DateTime.Parse(reader["user_birthday"].ToString());
             accountInfo.Phone = reader["uesr_phome"].ToString();
             return accountInfo;
         }
         return null;
     }
     catch
     {
         return null;
     }
     finally
     {
         con.Close();
     }
 }
Ejemplo n.º 6
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;
             }
         }
     }
 }
Ejemplo n.º 7
0
        private void skinButton_DishIncrease_Click(object sender, EventArgs e)
        {
            conn1.Open();
            string       dishid          = dataGridView2.SelectedRows[0].Cells[0].Value.ToString();
            string       dishquantity    = dataGridView2.SelectedRows[0].Cells[1].Value.ToString();
            string       dishinformation = dataGridView2.SelectedRows[0].Cells[2].Value.ToString();
            string       dishstatus      = dataGridView2.SelectedRows[0].Cells[3].Value.ToString();
            string       sql             = "insert into dish values('" + dishid + "','" + dishquantity + "','" + dishinformation + "','" + dishstatus + "')";
            MySQLCommand mys             = new MySQLCommand(sql, conn1);

            if (mys.ExecuteNonQuery() != -1)
            {
                MessageBox.Show("新增成功!", "恭喜");
                sql = "select * from dish";
                MySQLDataAdapter ada2 = new MySQLDataAdapter(sql, conn1);
                DataSet          ds2  = new DataSet();
                ada2.Fill(ds2);
                dataGridView2.DataSource = ds2.Tables[0];

                textBox_DishID.Clear();
                textBox_DishQuantity.Clear();
                textBox_DishInformation.Clear();
                textBox_DishStatus.Clear();
            }
            conn1.Close();
        }
Ejemplo n.º 8
0
        private void timer4_Tick(object sender, EventArgs e)
        {
            DBConn.Open();
            MySQLCommand DBComm   = new MySQLCommand("select * from `parkingsystem`.`login_record`", DBConn);
            MySQLCommand firstCmd = new MySQLCommand("set names big5", DBConn);

            firstCmd.ExecuteNonQuery();
            MySQLDataReader DBReader = DBComm.ExecuteReaderEx();

            DBReader.Read();
            do
            {
                if (DBReader.GetString(2) == "帳密正確")
                {
                    tSB_Exit.Enabled    = true;
                    tSB_search.Enabled  = true;
                    TSMI_help.Enabled   = true;
                    tabControl1.Enabled = true;
                    MySQLCommand    DBCom     = new MySQLCommand("UPDATE `parkingsystem`.`login_record` SET `result` = '成功登入' WHERE CONVERT( `login_record`.`date` USING utf8 ) = '" + DBReader.GetString(0) + "' LIMIT 1 ;", DBConn);
                    MySQLDataReader DBReader1 = DBCom.ExecuteReaderEx();
                    timer4.Enabled = false;
                    break;
                }
            } while (DBReader.Read());
            DBConn.Close();
        }
Ejemplo n.º 9
0
        private void timer5_Tick(object sender, EventArgs e)
        {
            DBConn.Open();
            MySQLCommand DBComm   = new MySQLCommand("select * from `parkingsystem`.`record`", DBConn);
            MySQLCommand firstCmd = new MySQLCommand("set names big5", DBConn);

            firstCmd.ExecuteNonQuery();
            MySQLDataReader DBReader = DBComm.ExecuteReaderEx();
            bool            s        = true;

            while (DBReader.Read())
            {
                if (DBReader.GetString(2) == "E" || DBReader.GetString(2) == "")
                {
                    tSSL_C.Text = "開啟";
                    s           = false;
                    break;
                }
            }
            if (s)
            {
                tSSL_C.Text = "關閉";
            }
            DBConn.Close();
        }
Ejemplo n.º 10
0
 private void skinButton_DishEdit_Click(object sender, EventArgs e)
 {
     conn1.Open();
     if (MessageBox.Show("确定要从数据库中修改这一行数据吗?", "数据无法恢复请慎重选择!", MessageBoxButtons.OKCancel) == DialogResult.OK)
     {
         string       dishid          = dataGridView2.SelectedRows[0].Cells[0].Value.ToString();
         string       dishquantity    = dataGridView2.SelectedRows[0].Cells[1].Value.ToString();
         string       dishinformation = dataGridView2.SelectedRows[0].Cells[2].Value.ToString();
         string       dishstatus      = dataGridView2.SelectedRows[0].Cells[3].Value.ToString();
         string       sql             = "update dish set dishid=" + dishid + ",dishquantity=" + dishquantity + ",dishinformation=" + dishinformation + ",dishstatus=" + dishstatus + " where dishid=" + dishid;
         MySQLCommand mys             = new MySQLCommand(sql, conn1);
         if (mys.ExecuteNonQuery() != -1)
         {
             MessageBox.Show("修改成功!", "恭喜");
             sql = "select * from dish";
             MySQLDataAdapter ada2 = new MySQLDataAdapter(sql, conn1);
             DataSet          ds2  = new DataSet();
             ada2.Fill(ds2);
             dataGridView2.DataSource = ds2.Tables[0];
         }
         else
         {
             MessageBox.Show("修改失败!", "提示");
         }
     }
     conn1.Close();
 }
Ejemplo n.º 11
0
        public PasteCode selectPasteCodeById(int id)
        {
            init();
            con.Open();
            string sql = "select * from paste_code where "
                         + "id = " + id;

            System.Diagnostics.Debug.WriteLine(sql);
            MySQLCommand    cmd       = new MySQLCommand(sql, con);
            MySQLDataReader reader    = cmd.ExecuteReaderEx();
            PasteCode       pasteCode = new PasteCode();

            while (reader.Read())
            {
                pasteCode.id     = (int)reader[0];
                pasteCode.poster = reader[1].ToString();
                System.Diagnostics.Debug.WriteLine(pasteCode.poster);
                pasteCode.language = reader[2].ToString();
                System.Diagnostics.Debug.WriteLine(pasteCode.language);
                pasteCode.languagemode = reader[3].ToString();
                System.Diagnostics.Debug.WriteLine(pasteCode.languagemode);
                pasteCode.theme = reader[4].ToString();
                System.Diagnostics.Debug.WriteLine(pasteCode.theme);
                byte[] buf = (byte[])reader[5];
                pasteCode.code = System.Text.Encoding.UTF8.GetString(buf);
                System.Diagnostics.Debug.WriteLine(pasteCode.code);
                pasteCode.time = reader[6].ToString();
                System.Diagnostics.Debug.WriteLine(pasteCode.time);
            }
            con.Close();
            return(pasteCode);
        }
Ejemplo n.º 12
0
 private void skinButton_MealCardEdit_Click(object sender, EventArgs e)
 {
     conn1.Open();
     if (MessageBox.Show("确定要从数据库中修改这一行数据吗?", "数据无法恢复请慎重选择!", MessageBoxButtons.OKCancel) == DialogResult.OK)
     {
         string       mealcardid          = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
         string       mealcardinformation = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
         string       mealcardstatus      = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
         string       sql = "update mealcard set mealcardid=" + mealcardid + ",mealcardinformation=" + mealcardinformation + ",mealcardstatus=" + mealcardstatus + " where mealcardid=" + mealcardid;
         MySQLCommand mys = new MySQLCommand(sql, conn1);
         if (mys.ExecuteNonQuery() != -1)
         {
             MessageBox.Show("修改成功!", "恭喜");
             sql = "select * from mealcard";
             MySQLDataAdapter ada1 = new MySQLDataAdapter(sql, conn1);
             DataSet          ds1  = new DataSet();
             ada1.Fill(ds1);
             dataGridView1.DataSource = ds1.Tables[0];
         }
         else
         {
             MessageBox.Show("修改失败!", "提示");
         }
     }
     conn1.Close();
 }
Ejemplo n.º 13
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;
        }
Ejemplo n.º 14
0
        private void Del_Click(object sender, RoutedEventArgs e)
        {
            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 = "delete from wf_model where model_name = '";
                sql += ((WFModel)listView1.SelectedItem).WFModel_Name;
                sql += "'";
                //MessageBox.Show(sql);
                MySQLCommand cmd = new MySQLCommand(sql, DBConn);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
            }
            catch (Exception e1)
            {
                MessageBox.Show("数据库连接失败,请检查网络连接或者数据库配置");
                return;
            }
            GetTemplateData();
        }
Ejemplo n.º 15
0
        protected int update(string sql)
        {
            MySQLConnection conn        = null;
            int             resultCount = -1;

            try
            {
                conn = dbMgr.DBConns.PopDBConnection();

                GameDBManager.SystemServerSQLEvents.AddEvent(string.Format("+SQL: {0}", sql), EventLevels.Important);

                MySQLCommand cmd = new MySQLCommand(sql, conn);

                try
                {
                    resultCount = cmd.ExecuteNonQuery();
                }
                catch (Exception)
                {
                    LogManager.WriteLog(LogTypes.Error, string.Format("向数据库更新数据失败: {0}", sql));
                }

                cmd.Dispose();
                cmd = null;
            }
            finally
            {
                if (null != conn)
                {
                    dbMgr.DBConns.PushDBConnection(conn);
                }
            }

            return(resultCount);
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            conn = new MySQLConnection(new MySQLConnectionString("10.125.103.139", "heartlink", "qwe", "123").AsString);
            cmd  = new MySQLCommand();
            da   = new MySQLDataAdapter();

            String pass = "******";
            String sql  = "select ID from students where password="******"ID = {0}", DBReader.GetString(0));
                }
            }
            finally
            {
                DBReader.Close();
                conn.Close();
            }
        }
        private JieriRecvKingItemData QueryRoleJieriRecvKing(DBManager dbMgr, string fromDate, string toDate, int roleID)
        {
            JieriRecvKingItemData result = null;
            MySQLConnection       conn   = null;

            try
            {
                conn = dbMgr.DBConns.PopDBConnection();
                string          cmdText = "SELECT t_roles.rid, t_roles.rname, t_roles.zoneid, x.totalrecv from t_roles,  (SELECT t_jierizengsong.receiver, SUM(t_jierizengsong.goodscnt) AS totalrecv " + string.Format(" FROM t_jierizengsong WHERE t_jierizengsong.receiver={0} AND sendtime>= '{1}' AND sendtime<='{2}') x ", roleID, fromDate, toDate) + " where t_roles.isdel=0 and t_roles.rid = x.receiver ";
                MySQLCommand    cmd     = new MySQLCommand(cmdText, conn);
                MySQLDataReader reader  = cmd.ExecuteReaderEx();
                if (reader.Read())
                {
                    result           = new JieriRecvKingItemData();
                    result.RoleID    = Convert.ToInt32(reader["rid"].ToString());
                    result.Rolename  = reader["rname"].ToString();
                    result.ZoneID    = Convert.ToInt32(reader["zoneid"].ToString());
                    result.TotalRecv = Convert.ToInt32(reader["totalrecv"].ToString());
                    result.Rank      = -1;
                }
                GameDBManager.SystemServerSQLEvents.AddEvent(string.Format("+SQL: {0}", cmdText), EventLevels.Important);
                cmd.Dispose();
            }
            finally
            {
                if (null != conn)
                {
                    dbMgr.DBConns.PushDBConnection(conn);
                }
            }
            return(result);
        }
Ejemplo n.º 18
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;
        }
Ejemplo n.º 19
0
        public int ExecuteNonQueryForInc(string commandStr)
        {
            connection.Open();

            MySQLCommand cmdTemp1 = (MySQLCommand)connection.CreateCommand();

            cmdTemp1.CommandText = "set names gbk";
            cmdTemp1.ExecuteNonQuery();

            command             = (MySQLCommand)connection.CreateCommand();
            command.CommandText = commandStr;
            command.ExecuteNonQuery();

            MySQLCommand cmdTemp2 = (MySQLCommand)connection.CreateCommand();

            cmdTemp2.CommandText = "select last_insert_id()";
            MySQLDataReader readerTemp;

            readerTemp = (MySQLDataReader)cmdTemp2.ExecuteReader();
            int LastID = -1;

            while (readerTemp.Read())
            {
                LastID = readerTemp.GetInt16(0);
            }

            return(LastID);
        }
Ejemplo n.º 20
0
        public GxMySQLDriverCSCursorDataReader(IGxConnectionManager connManager, GxDataRecord dr, IGxConnection connection, GxParameterCollection parameters,
                                               string stmt, int fetchSize, bool forFirst, int handle, bool cached, SlidingTime expiration, bool hasNested, bool dynStmt)
        {
            this.parameters = parameters;
            this.stmt       = stmt;
            this.fetchSize  = fetchSize;
            this.cache      = connection.ConnectionCache;
            this.cached     = cached;
            this.handle     = handle;
            this.isForFirst = forFirst;
            _connManager    = connManager;
            this.m_dr       = dr;
            this.readBytes  = 0;
            this.dynStmt    = dynStmt;
            con             = _connManager.IncOpenHandles(handle, m_dr.DataSource);
            con.CurrentStmt = stmt;
            con.MonitorEnter();
            GXLogging.Debug(log, "Open GxMySQLCursorDataReader handle:'" + handle);
            MySQLCommand cmd = (MySQLCommand)dr.GetCommand(con, stmt, parameters);

            cmd.ServerCursor = hasNested;
            cmd.FetchSize    = (uint)fetchSize;
            reader           = cmd.ExecuteReader();
            cache.SetAvailableCommand(stmt, false, dynStmt);
            open  = true;
            block = new GxArrayList(fetchSize);
            pos   = -1;
            if (cached)
            {
                key             = SqlUtil.GetKeyStmtValues(parameters, stmt, isForFirst);
                this.expiration = expiration;
            }
        }
Ejemplo n.º 21
0
 private static void PrepareCommand(MySQLCommand cmd, MySQLConnection conn, DbTransaction 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;
     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);
         }
     }
 }
Ejemplo n.º 22
0
        private void ButtonMagInfo_Click(object sender, EventArgs e)
        {
            MySQLConnection SQLconnection = new MySQLConnection(new MySQLConnectionString
                                                                    ("localhost", "DormitoryManage", "root", "123456").AsString);
            string SQLstr = "SELECT * FROM manager_info WHERE managerNumber = " + PublicValue.MAGNUM;

            SQLconnection.Open();
            MySQLCommand SQLcommand1 = new MySQLCommand("SET NAMES GB2312", SQLconnection);

            SQLcommand1.ExecuteNonQuery();   //执行设置字符集的语句
            MySQLCommand    SQLcommand2 = new MySQLCommand(SQLstr, SQLconnection);
            MySQLDataReader SQLreader   = (MySQLDataReader)SQLcommand2.ExecuteReader();

            if (SQLreader.Read())
            {
                this.TextBox1.Text = SQLreader["managerNumber"].ToString();
                this.TextBox2.Text = SQLreader["managerName"].ToString();
                this.TextBox3.Text = SQLreader["managerGender"].ToString();
                this.TextBox4.Text = SQLreader["managerAge"].ToString();
                this.TextBox5.Text = SQLreader["dormitoryNumber"].ToString();
                this.TextBox6.Text = SQLreader["managerPosition"].ToString();
                this.TextBox7.Text = SQLreader["managerPhone"].ToString();
                this.TextBox8.Text = SQLreader["managerPassword"].ToString();
            }
            SQLconnection.Close();
        }
Ejemplo n.º 23
0
        public void BuidConnections(MySQLConnectionString connStr, int maxCount)
        {
            MySQLConnection dbConn = null;

            for (int i = 0; i < maxCount; i++)
            {
                dbConn = new MySQLConnection(connStr.AsString);
                try
                {
                    dbConn.Open();
                }
                catch (Exception ex)
                {
                    DataHelper.WriteFormatExceptionLog(ex, "BuidConnections", false, false);
                    throw ex;
                }
                if (!string.IsNullOrEmpty(DBConnections.dbNames))
                {
                    MySQLCommand cmd = new MySQLCommand(string.Format("SET names '{0}'", DBConnections.dbNames), dbConn);
                    cmd.ExecuteNonQuery();
                }
                this.DBConns.Enqueue(dbConn);
            }
            this.SemaphoreClients = new Semaphore(maxCount, maxCount);
        }
Ejemplo n.º 24
0
 public void ExecuteSqlTran(Hashtable SQLStringList)
 {
     using (DbTransaction trans = this.DbConn.BeginTransaction())
     {
         using (MySQLCommand cmd = new MySQLCommand())
         {
             try
             {
                 foreach (object obj in SQLStringList)
                 {
                     DictionaryEntry  myDE     = (DictionaryEntry)obj;
                     string           cmdText  = myDE.Key.ToString();
                     MySQLParameter[] cmdParms = (MySQLParameter[])myDE.Value;
                     MyDbConnection3.PrepareCommand(cmd, this.DbConn, trans, cmdText, cmdParms);
                     int val = cmd.ExecuteNonQuery();
                     cmd.Parameters.Clear();
                     this.LogSql(cmdText);
                 }
                 trans.Commit();
             }
             catch
             {
                 trans.Rollback();
                 throw;
             }
         }
     }
 }
Ejemplo n.º 25
0
        public Dictionary <string, object> selectCommentByArticleId(int id)
        {
            init();
            con.Open();
            string sql = "select a.*,b.name from comment_list a right join user b on a.user_id = b.id "
                         + "where a.article_id = " + id;

            System.Diagnostics.Debug.WriteLine(sql);
            MySQLCommand    cmd       = new MySQLCommand(sql, con);
            MySQLDataReader reader    = cmd.ExecuteReaderEx();
            List <Comment>  comments  = new List <Comment>();
            List <string>   usernames = new List <string>();

            while (reader.Read())
            {
                comments.Add(new Comment((int)reader[0],
                                         (int)reader[1],
                                         (int)reader[2],
                                         encode.numToString(System.Text.Encoding.UTF8.GetString((byte[])reader[3])),
                                         reader[4].ToString()));
                usernames.Add((string)reader[5]);
            }
            Dictionary <string, object> dic = new Dictionary <string, object>();

            dic.Add("comments", comments);
            dic.Add("usernames", usernames);
            con.Close();
            return(dic);
        }
Ejemplo n.º 26
0
        public int contarEstudiantes()
        {
            int    cont      = 0;
            String CadenaSql = "select count(1) from estudiante ";

            try
            {
                MySQLDataReader ds;
                MySQLCommand    query;
                cnn.Open();
                query = new MySQLCommand(CadenaSql, cnn);
                ds    = query.ExecuteReaderEx();

                ds.Read();
                cont = int.Parse(ds.GetValue(0).ToString());
            }
            catch (MySQLException e)
            {
                System.Console.WriteLine(e.Message.ToString());
            }
            finally
            {
                cnn.Close();
            }
            return(cont);
        }
Ejemplo n.º 27
0
        public int insertNewPasteCode(PasteCode pasteCode)
        {
            init();
            con.Open();
            string sql = "insert into paste_code value(null,"
                         + "\"" + pasteCode.poster + "\","
                         + "\"" + pasteCode.language + "\","
                         + "\"" + pasteCode.languagemode + "\","
                         + "\"" + pasteCode.theme + "\","
                         + "\"" + pasteCode.code + "\","
                         + "\"" + pasteCode.time + "\")";

            System.Diagnostics.Debug.WriteLine(sql);
            MySQLCommand cmd = new MySQLCommand(sql, con);

            cmd.ExecuteNonQuery();
            sql = "select id from paste_code where "
                  + "poster = " + "\"" + pasteCode.poster + "\" && "
                  + "time = " + "\"" + pasteCode.time + "\"";
            System.Diagnostics.Debug.WriteLine(sql);
            cmd = new MySQLCommand(sql, con);
            MySQLDataReader reader = cmd.ExecuteReaderEx();
            int             id     = 0;

            while (reader.Read())
            {
                id = (int)reader[0];
            }
            con.Close();
            return(id);
        }
Ejemplo n.º 28
0
        public static List <string> Query()
        {
            List <string> ret = new List <string>();

            lock (conn)
            {
                try
                {
                    MySQLCommand commn;
                    commn = new MySQLCommand("create table if not exists monsqldb (text varchar(1000))", conn);
                    commn.ExecuteNonQuery();
                    commn = new MySQLCommand("select text from monsqldb", conn);
                    MySQLDataReader mdr = commn.ExecuteReaderEx();
                    while (mdr.Read())
                    {
                        ret.Add(mdr.GetString(0));
                    }
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show("数据库访问出错:" + ex.Message);
                }
            }
            return(ret);
        }
Ejemplo n.º 29
0
        public static string GetAward(DBManager dbMgr, int zoneID, int roleID)
        {
            string          result = "";
            MySQLConnection conn   = null;

            try
            {
                conn = dbMgr.DBConns.PopDBConnection();
                string          cmdText = string.Format("SELECT type,state FROM t_spread_award WHERE zoneID = '{0}' AND roleID = '{1}'", zoneID, roleID);
                MySQLCommand    cmd     = new MySQLCommand(cmdText, conn);
                MySQLDataReader reader  = cmd.ExecuteReaderEx();
                while (reader.Read())
                {
                    if (result != "")
                    {
                        result += "$";
                    }
                    result  = result + reader["type"].ToString() + "#";
                    result += reader["state"].ToString();
                }
                GameDBManager.SystemServerSQLEvents.AddEvent(string.Format("+SQL: {0}", cmdText), EventLevels.Important);
                cmd.Dispose();
            }
            finally
            {
                if (null != conn)
                {
                    dbMgr.DBConns.PushDBConnection(conn);
                }
            }
            return(result);
        }
Ejemplo n.º 30
0
        public void CheckPassword()
        {
            // 檢查帳密正確性
            // 權限設定還沒寫
            DBConn.Open();
            MySQLCommand DBComm   = new MySQLCommand("select * from `RFID_Project`.`user`", DBConn);
            MySQLCommand firstCmd = new MySQLCommand("set names big5", DBConn);

            firstCmd.ExecuteNonQuery();
            MySQLDataReader DBReader = DBComm.ExecuteReaderEx();
            bool            error    = true;

            DBReader.Read();
            do
            {
                string id       = ("" + DBReader.GetValue(0)); //id
                string passoord = ("" + DBReader.GetValue(1)); //password

                string enter = System.DateTime.Now.ToString("yyyy/MM/dd/ HH:mm:ss");
                if (tB_Id.Text == id && tB_Password.Text == passoord)
                {
                    error = false;
                    MySQLCommand    DBCom     = new MySQLCommand("INSERT INTO `RFID_Project`.`login_record` (`date`,`id`,`result`)VALUES ('" + enter + "','" + tB_Id.Text + "','" + "success" + "');", DBConn); //登錄記錄
                    MySQLDataReader DBReader1 = DBCom.ExecuteReaderEx();
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            } while (DBReader.Read());
            if (error)
            {
                MessageBox.Show("登錄檔作業失敗!! " + "\r\n" + "帳號或密碼有錯!請再確認");
            }
            DBConn.Close();
        }
Ejemplo n.º 31
0
        public LateWtEl(string flag)
        {
            InitializeComponent();
            string          SQLstr        = "\0";
            MySQLConnection SQLconnection = new MySQLConnection(new MySQLConnectionString
                                                                    ("localhost", "DormitoryManage", "root", "123456").AsString);

            if (flag == "0")
            {
                this.Text = "晚归信息";
                SQLstr    = "SELECT studentNumber as '学号',lateReturnTime as '晚归时间' FROM late_return WHERE studentNumber = " + PublicValue.STUNUM;
            }
            else if (flag == "1")
            {
                this.Text = "水电信息";
                SQLstr    = "SELECT studentNumber as '学号', dormitoryNumber as '公寓号',roomNumber as '寝室号',checkMonth as '日期',electricityConsumption as '用电量',electricityBill as '电费',waterConsumption" +
                            " as '用水量',waterBill as '水费' FROM Water_Electricity WHERE studentNumber = " + PublicValue.STUNUM;
            }
            SQLconnection.Open();
            MySQLCommand SQLcommand = new MySQLCommand("SET NAMES GB2312", SQLconnection);

            SQLcommand.ExecuteNonQuery();   //执行设置字符集的语句
            MySQLDataAdapter SQLadapter = new MySQLDataAdapter(SQLstr, SQLconnection);
            DataSet          set        = new DataSet();

            SQLadapter.Fill(set);
            DataGridView.DataSource = set.Tables[0];
            SQLconnection.Close();
        }
Ejemplo n.º 32
0
        public int validarUsuario(string u, string c)
        {
            int    cont      = 0;
            String CadenaSql = "select count(1) as cont from usuario where usuario = '" + u + "' and clave = md5('" + c + "')";

            try
            {
                MySQLDataReader ds;
                MySQLCommand    query;
                cnn.Open();
                query = new MySQLCommand(CadenaSql, cnn);
                ds    = query.ExecuteReaderEx();

                ds.Read();
                cont = int.Parse(ds.GetValue(0).ToString());
            }
            catch (MySQLException e)
            {
                System.Console.WriteLine(e.Message.ToString());
            }
            finally
            {
                cnn.Close();
            }
            return(cont);
        }
Ejemplo n.º 33
0
        private MySQLDataReader ExecSelect(string sql)
        {
            MySQLConnection conn = null;
            MySQLDataReader result;

            try
            {
                conn = DBManager.getInstance().DBConns.PopDBConnection();
                MySQLCommand cmd = new MySQLCommand(sql, conn);
                GameDBManager.SystemServerSQLEvents.AddEvent(string.Format("+SQL: {0}", sql), EventLevels.Important);
                MySQLDataReader reader = cmd.ExecuteReaderEx();
                cmd.Dispose();
                result = reader;
            }
            catch (Exception ex)
            {
                LogManager.WriteException(ex.Message);
                result = null;
            }
            finally
            {
                if (null != conn)
                {
                    DBManager.getInstance().DBConns.PushDBConnection(conn);
                }
            }
            return(result);
        }
Ejemplo n.º 34
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;
        }
Ejemplo n.º 35
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;
        }
Ejemplo n.º 36
0
        protected int delete(string sql, object[] param)
        {
            MySQLConnection conn        = null;
            int             resultCount = -1;

            try
            {
                conn = this.dbMgr.DBConns.PopDBConnection();
                GameDBManager.SystemServerSQLEvents.AddEvent(string.Format("+SQL: {0}", sql), EventLevels.Important);
                MySQLCommand cmd = new MySQLCommand();
                cmd.Connection  = conn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = sql;
                try
                {
                    resultCount = cmd.ExecuteNonQuery();
                }
                catch (Exception)
                {
                    LogManager.WriteLog(LogTypes.Error, string.Format("向数据库删除数据失败: {0}", sql), null, true);
                }
                cmd.Dispose();
                cmd = null;
            }
            finally
            {
                if (null != conn)
                {
                    this.dbMgr.DBConns.PushDBConnection(conn);
                }
            }
            return(resultCount);
        }
Ejemplo n.º 37
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();
 }
Ejemplo n.º 38
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, "�û��б�");
        }
Ejemplo n.º 39
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;
            }

        }
Ejemplo n.º 40
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;
             }
         }
     }
 }
Ejemplo n.º 41
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;
             }
         }
     }
 }
Ejemplo n.º 42
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];
         }
     }
 }
Ejemplo n.º 45
0
 public bool Login(LoginData data)
 {
     try
     {
         con.Open();
         sql = "SELECT user_password from users where user_id = " + data.User_id + "";
         MySQLCommand com = new MySQLCommand(sql, con);
         DbDataReader reader = com.ExecuteReader();
         if (reader.Read())
             if (reader["user_password"].ToString() == data.User_password)
                 return true;
         return false;
     }
     catch
     {
         return false;
     }
     finally
     {
         con.Close();
     }
 }
Ejemplo n.º 46
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();
        }
Ejemplo n.º 47
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;
            }
        }
Ejemplo n.º 48
0
        public void Insert(string tableName, IDictionary<string, string> item)
        {
            MySQLCommand commn = null;

            try
            {
                List<string> columns = item.Keys.ToList<string>();
                List<string> values = item.Values.ToList<string>();

                for (int index = 0; index < values.Count; index++)
                {
                    if (string.IsNullOrEmpty(values[index]))
                    {
                        values.RemoveAt(index);
                        columns.RemoveAt(index);
                        index--;
                    }
                }

                sqlCommnBuilder = new StringBuilder();
                sqlCommnBuilder.Append("INSERT INTO ");
                sqlCommnBuilder.Append(tableName);
                sqlCommnBuilder.Append(" (");
                for (int index = 0; index < columns.Count; index++)
                {
                    sqlCommnBuilder.Append(columns[index]);
                    sqlCommnBuilder.Append(", ");
                }
                sqlCommnBuilder.Remove(sqlCommnBuilder.Length - 2, 2);
                sqlCommnBuilder.Append(") VALUES ('");
                for (int index = 0; index < values.Count; index++)
                {
                    sqlCommnBuilder.Append(values[index]);
                    sqlCommnBuilder.Append("', '");
                }
                sqlCommnBuilder.Remove(sqlCommnBuilder.Length - 4, 4);
                sqlCommnBuilder.Append("')");
                conn.Open();
                Common.Log(sqlCommnBuilder.ToString());
                commn = new MySQLCommand();
                commn.CommandType = CommandType.Text;
                commn.CommandText = sqlCommnBuilder.ToString();
                commn.Connection = conn;
                int id = commn.ExecuteNonQuery();
                int t = id;
            }
            catch (MySQLException mySQLException)
            {
                Common.Log(mySQLException.ToString());
            }
            finally
            {
                if (commn != null)
                {
                    commn.Dispose();
                }

                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
        }
Ejemplo n.º 49
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); }

               //     }
        }
Ejemplo n.º 50
0
        public void Update(string tableName, string set, string where)
        {
            MySQLCommand commn = null;

            try
            {
                string insertString = "UPDATE TABLE_NAME SET SET_CONDITION WHERE WHERE_CONDITION";
                insertString = insertString.Replace("TABLE_NAME", tableName);
                insertString = insertString.Replace("SET_CONDITION", set);
                insertString = insertString.Replace("WHERE_CONDITION", where);
                Common.Log(insertString);
                conn.Open();
                commn = new MySQLCommand();
                commn.CommandText = insertString;
                commn.CommandType = CommandType.Text;
                commn.Connection = conn;
                commn.ExecuteNonQuery();
            }
            catch (MySQLException mySqlException)
            {
                Common.Log(mySqlException.ToString());
            }
            finally
            {
                if (commn != null)
                {
                    commn.Dispose();
                }

                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
        }
Ejemplo n.º 51
0
        public void Query(string tableName, string where, IDictionary<string, string> item)
        {
            MySQLCommand commn = null;
            MySQLDataReader mySqlReader = null;
            MySQLDataAdapter mySqlAdapter = null;
            try
            {
                conn.Open();
                Common.Log("Query columns from table: " + tableName);
                // Query table column name
                string[] columns = null;
                commn = new MySQLCommand();
                string queryString =
                    "SELECT column_name FROM information_schema.columns WHERE table_schema = 'DB_NAME' AND table_name = 'TABLE_NAME'";
                queryString = queryString.Replace("DB_NAME", databaseName);
                queryString = queryString.Replace("TABLE_NAME", tableName);
                commn.CommandText = queryString;
                commn.CommandType = CommandType.Text;
                commn.Connection = conn;
                mySqlAdapter = new MySQLDataAdapter(commn);
                DataSet myDataSet = new DataSet();
                mySqlAdapter.Fill(myDataSet);

                columns = new string[myDataSet.Tables[0].Rows.Count];

                for (int rowIndex = 0; rowIndex < myDataSet.Tables[0].Rows.Count; rowIndex++)
                {
                    columns[rowIndex] = myDataSet.Tables[0].Rows[rowIndex][0].ToString();
                }
                myDataSet.Clear();

                // Query table by where condition
                commn.Dispose();
                commn = new MySQLCommand();
                string queryString2 = "SELECT * FROM TABLE_NAME WHERE CONDITION";
                queryString2 = queryString2.Replace("TABLE_NAME", tableName);
                queryString2 = queryString2.Replace("CONDITION", where);
                commn.CommandText = queryString2;
                commn.CommandType = CommandType.Text;
                commn.Connection = conn;
                Common.Log(queryString2);
                mySqlAdapter = new MySQLDataAdapter(commn);
                myDataSet = new DataSet();
                mySqlAdapter.Fill(myDataSet);

                for (int columnIndex = 0; columnIndex < myDataSet.Tables[0].Columns.Count; columnIndex++)
                {
                    item[columns[columnIndex]] = myDataSet.Tables[0].Rows[0][columnIndex].ToString();
                }
            }
            catch (MySQLException mySqlException)
            {
                Common.Log(mySqlException.ToString());
            }
            finally
            {
                if (mySqlAdapter != null)
                {
                    mySqlAdapter.Dispose();
                }

                if (mySqlReader != null)
                {
                    mySqlReader.Close();
                    mySqlReader.Dispose();
                }

                if (commn != null)
                {
                    commn.Dispose();
                }

                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
        }
 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;
             }
         }
     }
 }
 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 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();

            }
        }
        //执行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;
                    }
                }
            }
        }
Ejemplo n.º 57
0
        private bool addOneUrl(int pos)
        {
            //添加第pos条团购条目信息
            string query;
            int link_id;
            MD5 md5 = new MD5CryptoServiceProvider(); ;
            //XmlNode oneUrl = lashouDocument.DocumentElement.ChildNodes[pos];
            oneUrl oneUrl = xmlparse.getOneUrl(pos);
            StatisticOutput sta = staContext.statistic(oneUrl);

            Console.WriteLine("Insert the data to the database....");
            query = "insert into links (site_id, url, title, description) values(5, \"" +
                sta.url + "\",\"" + sta.title + "\",\"" + sta.description + "\")";
            cmd = new MySQLDriverCS.MySQLCommand(query, conn);
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            query = "select link_id from links where url = \"" + sta.url + "\"";
            cmd = new MySQLDriverCS.MySQLCommand(query, conn);
            IDataReader dt = cmd.ExecuteReader();
            link_id = Convert.ToInt32(dt.GetSchemaTable().Rows[0]["link_id"]);
            foreach (DictionaryEntry de in sta.keywordList)
            {
                int keyword_id = 0;
                query = "select keyword_id from keywords where keyword = \"" + de.Key + "\"";
                cmd = new MySQLDriverCS.MySQLCommand(query, conn);
                dt = cmd.ExecuteReader();
                if (dt.GetSchemaTable().Rows.Count == 0)
                {
                    query = "insert into keywords (keyword) values (\"" + de.Key + "\")";
                    cmd = new MySQLDriverCS.MySQLCommand(query, conn);
                    cmd.ExecuteNonQuery();
                    cmd.Dispose();

                    query = "select keyword_id from keywords where keyword = \"" + de.Key + "\"";
                    cmd = new MySQLDriverCS.MySQLCommand(query, conn);
                    dt = cmd.ExecuteReader();
                    keyword_id = Convert.ToInt32(dt.GetSchemaTable().Rows[0]["keyword_id"]);
                }
                else
                    keyword_id = Convert.ToInt32(dt.GetSchemaTable().Rows[0]["keyword_id"]);
                byte[] hash = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(de.Key.ToString()));
                string flag;
                switch (hash[0] >> 4)
                {
                    case 10:
                        flag = "a";
                        break;
                    case 11:
                        flag = "b";
                        break;
                    case 12:
                        flag = "c";
                        break;
                    case 13:
                        flag = "d";
                        break;
                    case 14:
                        flag = "e";
                        break;
                    case 15:
                        flag = "f";
                        break;
                    default:
                        flag = (hash[0] >> 4).ToString();
                        break;
                }
                query = "insert into link_keyword" + flag + "(link_id, keyword_id, weight, time, feat, discount) values (" +
                    link_id + "," + keyword_id + "," + de.Value + "," + sta.time + "," + sta.feat + "," +
                    sta.discount + ")";
                cmd = new MySQLDriverCS.MySQLCommand(query, conn);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
            }
            Console.WriteLine("Write one link sucessfully!");
            return true;
        }
 private void Gbk()
 {
     MySQLCommand cmd = new MySQLCommand("set names gbk", conn);
     int r=cmd.ExecuteNonQuery();
 }
 private void Open()
 {
     //连接
     conn = new MySQLConnection(connectionString.AsString);
     //打开
     conn.Open();
     //解决乱码
     Gbk();
     //输入命令
     cmd = new MySQLCommand(sqlString, conn);
 }
 //命令
 private void Command()
 {
     cmd = new MySQLCommand();
     cmd.Connection = conn;
 }