CreateParameter() public method

Creates a new instance of a MySqlParameter object.
This method is a strongly-typed version of IDbCommand.CreateParameter.
public CreateParameter ( ) : MySqlParameter
return MySqlParameter
Exemplo n.º 1
0
        private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, CommandType cmdType, string cmdText, Dictionary<string, object> cmdParms)
        {
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
            {
                cmd.Transaction = trans;
            }
            cmd.CommandType = cmdType;
            if (cmdParms != null)
            {
                foreach (var param in cmdParms)
                {
                    var parameter = cmd.CreateParameter();
                    parameter.ParameterName = param.Key;
                    parameter.Value = param.Value;
                    cmd.Parameters.Add(parameter);
                }

            }
        }
Exemplo n.º 2
0
        protected override CustomerCommand CreateCommand(DataCommandConfig commandConfig)
        {
            //1.创建 Connection 对象【需要从连接池中获取连接对象,此处后续优化】
            //string strConn = ConfigurationManager.AppSettings["ConnectionString"];

            var dbConfig = DataManager.DatabaseDictionary[commandConfig.DataSourceID];
            string strConn = dbConfig.ConnectionString;

            MySqlConnection dbConnection = new MySqlConnection(strConn);

            //2.创建 Command 对象
            MySqlCommand command = new MySqlCommand(commandConfig.CommandText, dbConnection);
            command.CommandType = CommandType.Text;

            //3.填充参数列表
            foreach (ParameterConfig param in commandConfig.Parameters)
            {
                MySqlParameter parameter = command.CreateParameter();
                parameter.ParameterName = param.Name;
                parameter.DbType = param.DBType;
                parameter.Size = param.Size == 0 ? 4 : param.Size;
                parameter.Direction = ParameterDirection.Input; //默认是输入参数
                command.Parameters.Add(parameter);
            }
            CustomerCommand customerCmd = new CustomerCommand(command, DataBaseType.MySQL);
            return customerCmd;
        }
Exemplo n.º 3
0
        public void AddingParameterPreviouslyRemoved()
        {
            MySqlCommand cmd = new
              MySqlCommand("Insert into sometable(s1, s2) values(?p1, ?p2)");

              MySqlParameter param1 = cmd.CreateParameter();
              param1.ParameterName = "?p1";
              param1.DbType = DbType.String;
              param1.Value = "Ali Gel";

              cmd.Parameters.Add(param1);
              cmd.Parameters.RemoveAt(0);
              cmd.Parameters.Add(param1);
        }
        /// <summary>
        /// Adds the parameters to a MySQL command
        /// </summary>
        /// <param name="commandText">The MySQL query to execute</param>
        /// <param name="parameters">Parameters to pass to the MySQL query</param>
        private static void AddParameters(MySqlCommand command, Dictionary<string, object> parameters)
        {
            if (parameters == null)
            {
                return;
            }

            foreach (var param in parameters)
            {
                var parameter = command.CreateParameter();
                parameter.ParameterName = param.Key;
                parameter.Value = param.Value ?? DBNull.Value;
                command.Parameters.Add(parameter);
            }
        }
        public void CallingStoredFunctionasProcedure()
        {
            if (Version < new Version(5, 0)) return;

              execSQL("CREATE FUNCTION fnTest(valin int) RETURNS INT " +
              " LANGUAGE SQL DETERMINISTIC BEGIN return valin * 2; END");
              MySqlCommand cmd = new MySqlCommand("fnTest", conn);
              cmd.CommandType = CommandType.StoredProcedure;
              cmd.Parameters.AddWithValue("?valin", 22);
              MySqlParameter retVal = cmd.CreateParameter();
              retVal.ParameterName = "?retval";
              retVal.MySqlDbType = MySqlDbType.Int32;
              retVal.Direction = ParameterDirection.ReturnValue;
              cmd.Parameters.Add(retVal);
              if (prepare) cmd.Prepare();
              cmd.ExecuteNonQuery();
              Assert.AreEqual(44, cmd.Parameters[1].Value);
        }
Exemplo n.º 6
0
        public bool Save(MySqlConnection dbcon, bool forceFullData)
        {
            bool result = true;
            using (Utils.ProgressBlock fixpr = new ProgressBlock(this, STR_SAVING, STR_SAVINGDATA, 1, 0))
            {
                if (dbcon != null)
                {
                    string[] custAttr = Core.Geocaches.CustomAttributes;
                    List<string> activeAttr = new List<string>();
                    using (MySqlCommand cmd = new MySqlCommand("select field_name from geocache_cfields", dbcon))
                    using (MySqlDataReader dr = cmd.ExecuteReader())
                        while (dr.Read())
                        {
                            activeAttr.Add(string.Format("{0}", dr["field_name"]));
                        }

                    foreach (string s in activeAttr)
                    {
                        if (!custAttr.Contains(s) && ColumnExists(dbcon, "geocache", string.Format("_{0}", s)))
                        {
                            //drop column not supported!
                        }
                    }
                    //geocache_cfields
                    using (MySqlCommand cmd = new MySqlCommand("delete from geocache_cfields", dbcon))
                        cmd.ExecuteNonQuery();
                    foreach (string s in custAttr)
                    {
                        if (!activeAttr.Contains(s))
                        {
                            using (MySqlCommand cmd = new MySqlCommand(string.Format("insert into geocache_cfields (field_name) values ('{0}')", s), dbcon))
                                cmd.ExecuteNonQuery();
                        }
                        if (!ColumnExists(dbcon, "geocache", string.Format("_{0}", s)))
                        {
                            using (MySqlCommand cmd = new MySqlCommand(string.Format("alter table geocache add _{0} text)", s), dbcon))
                                cmd.ExecuteNonQuery();
                        }
                    }

                    //delete geoacches that are not in the list anymore.
                    string[] c = (from string a in _geocachesInDB.Keys select a).ToArray();
                    using (MySqlCommand cmd = dbcon.CreateCommand())
                        for (int i = 0; i < c.Length; i++)
                        {
                            if (Utils.DataAccess.GetGeocache(Core.Geocaches, c[i]) == null)
                            {
                                cmd.CommandText = string.Format("delete from geocache where code='{0}'", c[i]);
                                cmd.ExecuteNonQuery();
                                _geocachesInDB.Remove(c[i]);
                            }
                        }

                    //reset selection
                    using (MySqlCommand cmd = new MySqlCommand("update geocache set selected=0", dbcon))
                        cmd.ExecuteNonQuery();

                    //now get all the selected and data changed geocaches
                    List<Framework.Data.Geocache> gclist = (from Framework.Data.Geocache wp in Core.Geocaches
                                                            where wp.Selected || !wp.Saved
                                                            select wp).ToList();
                    if (gclist.Count > 0)
                    {
                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_SAVING, STR_SAVINGGEOCACHES, gclist.Count, 0))
                        {
                            string updateSqlFull = "update geocache set id=@id, name=@name, datafromdate=@datafromdate, lat=@lat, lon=@lon, disttocent=@disttocent, angletocent=@angletocent, available=@available, archived=@archived, country=@country, state=@state, cachetype=@cachetype, placedby=@placedby, owner=@owner, ownerid=@ownerid, container=@container, terrain=@terrain, difficulty=@difficulty, shortdescr=@shortdescr, shortdescrhtml=@shortdescrhtml, longdescr=@longdescr, longdescrhtml=@longdescrhtml, encodedhints=@encodedhints, url=@url, memberonly=@memberonly, customcoords=@customcoords, attrids=@attrids, favorites=@favorites, selected=@selected, municipality=@municipality, city=@city, customlat=@customlat, customlon=@customlon, notes=@notes, publiceddate=@publiceddate, personalnote=@personalnote, flagged=@flagged, found=@found, locked=@locked where code=@code";
                            string insertSqlFull = "insert into geocache (id, code, name, datafromdate, lat, lon, disttocent, angletocent, available, archived, country, state, cachetype, placedby, owner, ownerid, container, terrain, difficulty, shortdescr, shortdescrhtml, longdescr, longdescrhtml, encodedhints, url, memberonly, customcoords, attrids, favorites, selected, municipality, city, customlat, customlon, notes, publiceddate, personalnote, flagged, found, locked) values (@id, @code, @name, @datafromdate, @lat, @lon, @disttocent, @angletocent, @available, @archived, @country, @state, @cachetype, @placedby, @owner, @ownerid, @container, @terrain, @difficulty, @shortdescr, @shortdescrhtml, @longdescr, @longdescrhtml, @encodedhints, @url, @memberonly, @customcoords, @attrids, @favorites, @selected, @municipality, @city, @customlat, @customlon, @notes, @publiceddate, @personalnote, @flagged, @found, @locked)";

                            string updateSqlShort = "update geocache set id=@id, name=@name, datafromdate=@datafromdate, lat=@lat, lon=@lon, disttocent=@disttocent, angletocent=@angletocent, available=@available, archived=@archived, country=@country, state=@state, cachetype=@cachetype, placedby=@placedby, owner=@owner, ownerid=@ownerid, container=@container, terrain=@terrain, difficulty=@difficulty, encodedhints=@encodedhints, url=@url, memberonly=@memberonly, customcoords=@customcoords, attrids=@attrids, favorites=@favorites, selected=@selected, municipality=@municipality, city=@city, customlat=@customlat, customlon=@customlon, notes=@notes, publiceddate=@publiceddate, personalnote=@personalnote, flagged=@flagged, found=@found, locked=@locked where code=@code";
                            string insertSqlShort = "insert into geocache (id, code, name, datafromdate, lat, lon, disttocent, angletocent, available, archived, country, state, cachetype, placedby, owner, ownerid, container, terrain, difficulty, encodedhints, url, memberonly, customcoords, attrids, favorites, selected, municipality, city, customlat, customlon, notes, publiceddate, personalnote, flagged, found, locked) values (@id, @code, @name, @datafromdate, @lat, @lon, @disttocent, @angletocent, @available, @archived, @country, @state, @cachetype, @placedby, @owner, @ownerid, @container, @terrain, @difficulty, @encodedhints, @url, @memberonly, @customcoords, @attrids, @favorites, @selected, @municipality, @city, @customlat, @customlon, @notes, @publiceddate, @personalnote, @flagged, @found, @locked)";

                            using (MySqlCommand cmd = dbcon.CreateCommand())
                            {
                                cmd.CommandType = CommandType.Text;
                                DbParameter par = cmd.CreateParameter();
                                par.ParameterName = "@id";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@code";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@name";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@datafromdate";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@lat";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@lon";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@disttocent";
                                par.DbType = DbType.Int64;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@angletocent";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@available";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@archived";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@country";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@state";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@cachetype";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@placedby";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@owner";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@ownerid";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@container";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@terrain";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@difficulty";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@shortdescr";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@shortdescrhtml";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@longdescr";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@longdescrhtml";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@encodedhints";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@url";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@memberonly";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@customcoords";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@attrids";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@favorites";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@selected";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@municipality";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@city";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@customlat";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@customlon";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@notes";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@publiceddate";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@personalnote";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@flagged";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@found";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@locked";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);

                                foreach (string s in custAttr)
                                {
                                    par = cmd.CreateParameter();
                                    par.ParameterName = string.Format("@_{0}", s);
                                    par.DbType = DbType.String;
                                    cmd.Parameters.Add(par);
                                }

                                cmd.Prepare();

                                StringBuilder sb = new StringBuilder();

                                //using (MySqlTransaction trans = dbcon.BeginTransaction())
                                {
                                    //cmd.Transaction = trans;

                                    int index = 0;
                                    int procStep = 0;
                                    foreach (Framework.Data.Geocache gc in gclist)
                                    {
                                        index++;
                                        procStep++;
                                        if (!gc.Saved)
                                        {
                                            cmd.Parameters["@id"].Value = gc.ID ?? "";
                                            cmd.Parameters["@code"].Value = gc.Code;
                                            cmd.Parameters["@name"].Value = gc.Name ?? "";
                                            cmd.Parameters["@datafromdate"].Value = gc.DataFromDate.ToUniversalTime().ToString("u");
                                            cmd.Parameters["@lat"].Value = gc.Lat;
                                            cmd.Parameters["@lon"].Value = gc.Lon;
                                            cmd.Parameters["@disttocent"].Value = gc.DistanceToCenter;
                                            cmd.Parameters["@angletocent"].Value = gc.AngleToCenter;
                                            cmd.Parameters["@available"].Value = gc.Available ? 1 : 0;
                                            cmd.Parameters["@archived"].Value = gc.Archived ? 1 : 0;
                                            cmd.Parameters["@country"].Value = gc.Country ?? "";
                                            cmd.Parameters["@state"].Value = gc.State ?? "";
                                            cmd.Parameters["@cachetype"].Value = gc.GeocacheType == null ? -1 : gc.GeocacheType.ID;
                                            cmd.Parameters["@placedby"].Value = gc.PlacedBy ?? "";
                                            cmd.Parameters["@owner"].Value = gc.Owner ?? "";
                                            cmd.Parameters["@ownerid"].Value = gc.OwnerId ?? "";
                                            cmd.Parameters["@container"].Value = gc.Container == null ? -1 : gc.Container.ID;
                                            cmd.Parameters["@terrain"].Value = gc.Terrain;
                                            cmd.Parameters["@difficulty"].Value = gc.Difficulty;
                                            if (forceFullData || gc.FullDataLoaded)
                                            {
                                                cmd.Parameters["@shortdescr"].Value = gc.ShortDescription ?? "";
                                                cmd.Parameters["@shortdescrhtml"].Value = gc.ShortDescriptionInHtml ? 1 : 0;
                                                cmd.Parameters["@longdescr"].Value = gc.LongDescription ?? "";
                                                cmd.Parameters["@longdescrhtml"].Value = gc.LongDescriptionInHtml ? 1 : 0;
                                            }
                                            cmd.Parameters["@encodedhints"].Value = gc.EncodedHints ?? "";
                                            cmd.Parameters["@url"].Value = gc.Url ?? "";
                                            cmd.Parameters["@memberonly"].Value = gc.MemberOnly ? 1 : 0;
                                            cmd.Parameters["@customcoords"].Value = gc.CustomCoords ? 1 : 0;
                                            sb.Length = 0;
                                            foreach (int attrId in gc.AttributeIds)
                                            {
                                                sb.AppendFormat("|{0}|", attrId);
                                            }
                                            cmd.Parameters["@attrids"].Value = sb.ToString();
                                            cmd.Parameters["@favorites"].Value = gc.Favorites;
                                            cmd.Parameters["@selected"].Value = gc.Selected ? 1 : 0;
                                            cmd.Parameters["@municipality"].Value = gc.Municipality ?? "";
                                            cmd.Parameters["@city"].Value = gc.City ?? "";
                                            if (gc.CustomLat == null)
                                            {
                                                cmd.Parameters["@customlat"].Value = DBNull.Value;
                                            }
                                            else
                                            {
                                                cmd.Parameters["@customlat"].Value = gc.CustomLat;
                                            }
                                            if (gc.CustomLon == null)
                                            {
                                                cmd.Parameters["@customlon"].Value = DBNull.Value;
                                            }
                                            else
                                            {
                                                cmd.Parameters["@customlon"].Value = gc.CustomLon;
                                            }
                                            cmd.Parameters["@notes"].Value = gc.Notes ?? "";
                                            cmd.Parameters["@publiceddate"].Value = gc.PublishedTime.ToUniversalTime().ToString("u");
                                            cmd.Parameters["@personalnote"].Value = gc.PersonaleNote ?? "";
                                            cmd.Parameters["@flagged"].Value = gc.Flagged ? 1 : 0;
                                            cmd.Parameters["@found"].Value = gc.Found ? 1 : 0;
                                            cmd.Parameters["@locked"].Value = gc.Locked ? 1 : 0;

                                            foreach (string s in custAttr)
                                            {
                                                object o = gc.GetCustomAttribute(s);
                                                if (o == null)
                                                {
                                                    cmd.Parameters[string.Format("@_{0}", s)].Value = DBNull.Value;
                                                }
                                                else
                                                {
                                                    cmd.Parameters[string.Format("@_{0}", s)].Value = o.ToString();
                                                }
                                            }

                                            bool indb = _geocachesInDB[gc.Code] != null;
                                            if (forceFullData || gc.FullDataLoaded)
                                            {
                                                cmd.CommandText = updateSqlFull;
                                                if (!indb || cmd.ExecuteNonQuery() == 0)
                                                {
                                                    cmd.CommandText = insertSqlFull;
                                                    cmd.ExecuteNonQuery();
                                                    if (!indb)
                                                    {
                                                        _geocachesInDB[gc.Code] = gc.Code;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                cmd.CommandText = updateSqlShort;
                                                if (!indb || cmd.ExecuteNonQuery() == 0)
                                                {
                                                    cmd.CommandText = insertSqlShort;
                                                    cmd.ExecuteNonQuery();
                                                    if (!indb)
                                                    {
                                                        _geocachesInDB[gc.Code] = gc.Code;
                                                    }
                                                }
                                            }
                                            gc.Saved = true;
                                        }
                                        else if (gc.Selected)
                                        {
                                            cmd.CommandText = string.Format("update geocache set selected=1 where code='{0}'", gc.Code);
                                            cmd.ExecuteNonQuery();
                                        }
                                        if (procStep >= 200)
                                        {
                                            progress.UpdateProgress(STR_SAVING, STR_SAVINGGEOCACHES, gclist.Count, index);
                                            procStep = 0;
                                        }
                                    }
                                    //trans.Commit();
                                }
                            }
                        }
                    }

                    //delete logs that are not in the list anymore.
                    c = (from string a in _logsInDB.Keys select a).ToArray();
                    using (MySqlCommand cmd = dbcon.CreateCommand())
                        for (int i = 0; i < c.Length; i++)
                        {
                            if (Utils.DataAccess.GetLog(Core.Logs, c[i]) == null)
                            {
                                cmd.CommandText = string.Format("delete from log where id='{0}'", c[i]);
                                cmd.ExecuteNonQuery();
                                _logsInDB.Remove(c[i]);
                            }
                        }

                    //now get all the selected and data changed geocaches
                    List<Framework.Data.Log> lglist = (from Framework.Data.Log wp in Core.Logs
                                                       where !wp.Saved
                                                       select wp).ToList();
                    if (lglist.Count > 0)
                    {
                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_SAVING, STR_SAVINGLOGS, lglist.Count, 0))
                        {
                            // tbcode, finderid, logtext, encoded
                            string updateSqlFull = "update log set gccode=@gccode, tbcode=@tbcode, date=@date, finder=@finder, finderid=@finderid, logtext=@logtext, encoded=@encoded, datafromdate=@datafromdate, logtype=@logtype where id=@id";
                            string insertSqlFull = "insert into log (id, gccode, tbcode, date, finder, finderid, logtext, encoded, datafromdate, logtype) values (@id, @gccode, @tbcode, @date, @finder, @finderid, @logtext, @encoded, @datafromdate, @logtype)";

                            string updateSqlShort = "update log set gccode=@gccode, date=@date, finder=@finder, datafromdate=@datafromdate, logtype=@logtype where id=@id";
                            string insertSqlShort = "insert into log (id, gccode, date, finder, datafromdate, logtype) values (@id, @gccode, @date, @finder, @datafromdate, @logtype)";

                            using (MySqlCommand cmd = dbcon.CreateCommand())
                            {
                                cmd.CommandType = CommandType.Text;
                                cmd.Parameters.Clear();
                                DbParameter par = cmd.CreateParameter();
                                par.ParameterName = "@id";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@gccode";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@tbcode";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@date";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@finder";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@finderid";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@logtext";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@encoded";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@datafromdate";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@logtype";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);

                                //cmd.Prepare();

                                //using (MySqlTransaction trans = dbcon.BeginTransaction())
                                {
                                    //cmd.Transaction = trans;

                                    int index = 0;
                                    int procStep = 0;
                                    foreach (Framework.Data.Log lg in lglist)
                                    {
                                        index++;
                                        procStep++;

                                        cmd.Parameters["@id"].Value = lg.ID;
                                        cmd.Parameters["@gccode"].Value = lg.GeocacheCode;
                                        cmd.Parameters["@date"].Value = lg.Date.ToUniversalTime().ToString("u");
                                        cmd.Parameters["@finder"].Value = lg.Finder ?? "";
                                        cmd.Parameters["@datafromdate"].Value = lg.DataFromDate.ToUniversalTime().ToString("u");
                                        cmd.Parameters["@logtype"].Value = lg.LogType == null ? -1 : lg.LogType.ID;
                                        if (forceFullData || lg.FullDataLoaded)
                                        {
                                            cmd.Parameters["@tbcode"].Value = lg.TBCode ?? "";
                                            cmd.Parameters["@finderid"].Value = lg.FinderId ?? "";
                                            cmd.Parameters["@logtext"].Value = lg.Text ?? "";
                                            cmd.Parameters["@encoded"].Value = lg.Encoded ? 1 : 0;
                                        }

                                        bool indb = _logsInDB[lg.ID] != null;
                                        if (forceFullData || lg.FullDataLoaded)
                                        {
                                            cmd.CommandText = updateSqlFull;
                                            if (!indb || cmd.ExecuteNonQuery() == 0)
                                            {
                                                cmd.CommandText = insertSqlFull;
                                                cmd.ExecuteNonQuery();
                                                if (!indb)
                                                {
                                                    _logsInDB[lg.ID] = lg.ID;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            cmd.CommandText = updateSqlShort;
                                            if (!indb || cmd.ExecuteNonQuery() == 0)
                                            {
                                                cmd.CommandText = insertSqlShort;
                                                cmd.ExecuteNonQuery();
                                                if (!indb)
                                                {
                                                    _logsInDB[lg.ID] = lg.ID;
                                                }
                                            }
                                        }
                                        lg.Saved = true;

                                        if (procStep >= 2000)
                                        {
                                            progress.UpdateProgress(STR_SAVING, STR_SAVINGLOGS, lglist.Count, index);
                                            procStep = 0;
                                        }
                                    }
                                    //trans.Commit();

                                }
                            }
                        }
                    }



                    //delete log images that are not in the list anymore.
                    c = (from string a in _logimgsInDB.Keys select a).ToArray();
                    using (MySqlCommand cmd = dbcon.CreateCommand())
                        for (int i = 0; i < c.Length; i++)
                        {
                            if (Utils.DataAccess.GetLogImage(Core.LogImages, c[i]) == null)
                            {
                                cmd.CommandText = string.Format("delete from logimage where id='{0}'", c[i]);
                                cmd.ExecuteNonQuery();
                                _logimgsInDB.Remove(c[i]);
                            }
                        }

                    //now get all the selected and data changed geocaches
                    List<Framework.Data.LogImage> imglist = (from Framework.Data.LogImage wp in Core.LogImages
                                                             where !wp.Saved
                                                             select wp).ToList();
                    if (imglist.Count > 0)
                    {
                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_SAVING, STR_SAVINGLOGIMAGES, imglist.Count, 0))
                        {
                            string updateSql = "update logimage set logid=@logid, url=@url, name=@name, datafromdate=@datafromdate where id=@id";
                            string insertSql = "insert into logimage (id, logid, url, name, datafromdate) values (@id, @logid, @url, @name, @datafromdate)";

                            using (MySqlCommand cmd = dbcon.CreateCommand())
                            {

                                cmd.CommandType = CommandType.Text;
                                cmd.Parameters.Clear();
                                DbParameter par = cmd.CreateParameter();
                                par.ParameterName = "@id";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@logid";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@url";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@name";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@datafromdate";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                //cmd.Prepare();

                                //using (SqlTransaction trans = dbcon.BeginTransaction())
                                {
                                    //cmd.Transaction = trans;

                                    int index = 0;
                                    int procStep = 0;
                                    foreach (Framework.Data.LogImage lg in imglist)
                                    {
                                        index++;
                                        procStep++;

                                        cmd.Parameters["@id"].Value = lg.ID;
                                        cmd.Parameters["@logid"].Value = lg.LogID ?? "";
                                        cmd.Parameters["@url"].Value = lg.Url ?? "";
                                        cmd.Parameters["@name"].Value = lg.Name ?? "";
                                        cmd.Parameters["@datafromdate"].Value = lg.DataFromDate.ToUniversalTime().ToString("u");

                                        bool indb = _logimgsInDB[lg.ID] != null;
                                        cmd.CommandText = updateSql;
                                        if (!indb || cmd.ExecuteNonQuery() == 0)
                                        {
                                            cmd.CommandText = insertSql;
                                            cmd.ExecuteNonQuery();
                                            if (!indb)
                                            {
                                                _logimgsInDB[lg.ID] = lg.ID;
                                            }
                                        }
                                        lg.Saved = true;

                                        if (procStep >= 500)
                                        {
                                            progress.UpdateProgress(STR_SAVING, STR_SAVINGLOGIMAGES, imglist.Count, index);
                                            procStep = 0;
                                        }
                                    }
                                    //trans.Commit();
                                }
                            }
                        }
                    }


                    c = (from string a in _wptsInDB.Keys select a).ToArray();
                    using (MySqlCommand cmd = dbcon.CreateCommand())
                        for (int i = 0; i < c.Length; i++)
                        {
                            if (Utils.DataAccess.GetWaypoint(Core.Waypoints, c[i]) == null)
                            {
                                cmd.CommandText = string.Format("delete from waypoint where code='{0}'", c[i]);
                                cmd.ExecuteNonQuery();
                                _wptsInDB.Remove(c[i]);
                            }
                        }

                    //now get all the selected and data changed geocaches
                    List<Framework.Data.Waypoint> wplist = (from Framework.Data.Waypoint wp in Core.Waypoints
                                                            where !wp.Saved
                                                            select wp).ToList();
                    if (wplist.Count > 0)
                    {
                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_SAVING, STR_SAVINGWAYPOINTS, wplist.Count, 0))
                        {
                            string updateSql = "update waypoint set id=@id, geocachecode=@geocachecode, name=@name, datafromdate=@datafromdate, comment=@comment, description=@description, url=@url, urlname=@urlname, wptype=@wptype, lat=@lat, lon=@lon, time=@time where code=@code";
                            string insertSql = "insert into waypoint (id, code, geocachecode, name, datafromdate, comment, description, url, urlname, wptype, lat, lon, time) values (@id, @code, @geocachecode, @name, @datafromdate, @comment, @description, @url, @urlname, @wptype, @lat, @lon, @time)";

                            using (MySqlCommand cmd = dbcon.CreateCommand())
                            {

                                cmd.CommandType = CommandType.Text;
                                cmd.Parameters.Clear();
                                DbParameter par = cmd.CreateParameter();
                                par.ParameterName = "@id";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@code";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@url";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@name";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@datafromdate";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@geocachecode";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@comment";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@description";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@urlname";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@wptype";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@lat";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@lon";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@time";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                //cmd.Prepare();

                                //using (SqlTransaction trans = dbcon.BeginTransaction())
                                {
                                    //cmd.Transaction = trans;

                                    int index = 0;
                                    int procStep = 0;
                                    foreach (Framework.Data.Waypoint wp in wplist)
                                    {
                                        index++;
                                        procStep++;

                                        cmd.Parameters["@id"].Value = wp.ID;
                                        cmd.Parameters["@code"].Value = wp.Code ?? "";
                                        cmd.Parameters["@url"].Value = wp.Url ?? "";
                                        cmd.Parameters["@urlname"].Value = wp.UrlName ?? "";
                                        cmd.Parameters["@name"].Value = wp.Name ?? "";
                                        cmd.Parameters["@comment"].Value = wp.Comment ?? "";
                                        cmd.Parameters["@geocachecode"].Value = wp.GeocacheCode ?? "";
                                        cmd.Parameters["@description"].Value = wp.Description ?? "";
                                        cmd.Parameters["@datafromdate"].Value = wp.DataFromDate.ToUniversalTime().ToString("u");
                                        cmd.Parameters["@time"].Value = wp.Time.ToUniversalTime().ToString("u");
                                        cmd.Parameters["@wptype"].Value = wp.WPType.ID;
                                        if (wp.Lat == null)
                                        {
                                            cmd.Parameters["@lat"].Value = DBNull.Value;
                                        }
                                        else
                                        {
                                            cmd.Parameters["@lat"].Value = (double)(float)wp.Lat;
                                        }
                                        if (wp.Lon == null)
                                        {
                                            cmd.Parameters["@lon"].Value = DBNull.Value;
                                        }
                                        else
                                        {
                                            cmd.Parameters["@lon"].Value = wp.Lon;
                                        }

                                        bool indb = _wptsInDB[wp.Code] != null;
                                        cmd.CommandText = updateSql;
                                        if (!indb || cmd.ExecuteNonQuery() == 0)
                                        {
                                            cmd.CommandText = insertSql;
                                            cmd.ExecuteNonQuery();
                                            if (!indb)
                                            {
                                                _wptsInDB[wp.Code] = wp.Code;
                                            }
                                        }
                                        wp.Saved = true;

                                        if (procStep >= 500)
                                        {
                                            progress.UpdateProgress(STR_SAVING, STR_SAVINGWAYPOINTS, wplist.Count, index);
                                            procStep = 0;
                                        }
                                    }
                                    //trans.Commit();
                                }
                            }
                        }
                    }

                    int[] ci = (from int a in _usrwptsInDB.Keys select a).ToArray();
                    using (MySqlCommand cmd = new MySqlCommand("", dbcon))
                        for (int i = 0; i < ci.Length; i++)
                        {
                            if (Utils.DataAccess.GetUserWaypoint(Core.UserWaypoints, ci[i]) == null)
                            {
                                cmd.CommandText = string.Format("delete from userwaypoint where id={0}", ci[i]);
                                cmd.ExecuteNonQuery();
                                _usrwptsInDB.Remove(ci[i]);
                            }
                        }

                    //now get all the selected and data changed geocaches
                    List<Framework.Data.UserWaypoint> usrwplist = (from Framework.Data.UserWaypoint wp in Core.UserWaypoints
                                                                   where !wp.Saved
                                                                   select wp).ToList();
                    if (usrwplist.Count > 0)
                    {
                        string updateSql = "update userwaypoint set geocachecode=@geocachecode, description=@description, lat=@lat, lon=@lon, time=@time where id=@id";
                        string insertSql = "insert into userwaypoint (id, geocachecode, description, lat, lon, time) values (@id, @geocachecode, @description, @lat, @lon, @time)";

                        using (MySqlCommand cmd = new MySqlCommand("", dbcon))
                        {

                            cmd.CommandType = CommandType.Text;
                            cmd.Parameters.Clear();
                            DbParameter par = cmd.CreateParameter();
                            par.ParameterName = "@id";
                            par.DbType = DbType.Int32;
                            cmd.Parameters.Add(par);
                            par = cmd.CreateParameter();
                            par.ParameterName = "@geocachecode";
                            par.DbType = DbType.String;
                            cmd.Parameters.Add(par);
                            par = cmd.CreateParameter();
                            par.ParameterName = "@description";
                            par.DbType = DbType.String;
                            cmd.Parameters.Add(par);
                            par = cmd.CreateParameter();
                            par.ParameterName = "@lat";
                            par.DbType = DbType.Double;
                            cmd.Parameters.Add(par);
                            par = cmd.CreateParameter();
                            par.ParameterName = "@lon";
                            par.DbType = DbType.Double;
                            cmd.Parameters.Add(par);
                            par = cmd.CreateParameter();
                            par.ParameterName = "@time";
                            par.DbType = DbType.String;
                            cmd.Parameters.Add(par);
                            //cmd.Prepare();

                            //using (DbTransaction trans = dbcon.BeginTransaction())
                            {
                                //cmd.Transaction = trans;
                                foreach (Framework.Data.UserWaypoint wp in usrwplist)
                                {
                                    cmd.Parameters["@id"].Value = wp.ID;
                                    cmd.Parameters["@geocachecode"].Value = wp.GeocacheCode ?? "";
                                    cmd.Parameters["@description"].Value = wp.Description ?? "";
                                    cmd.Parameters["@time"].Value = wp.Date.ToUniversalTime().ToString("u");
                                    cmd.Parameters["@lat"].Value = (double)wp.Lat;
                                    cmd.Parameters["@lon"].Value = wp.Lon;

                                    bool indb = _usrwptsInDB[wp.ID] != null;
                                    cmd.CommandText = updateSql;
                                    if (!indb || cmd.ExecuteNonQuery() == 0)
                                    {
                                        cmd.CommandText = insertSql;
                                        cmd.ExecuteNonQuery();
                                        if (!indb)
                                        {
                                            _usrwptsInDB[wp.ID] = wp.ID;
                                        }
                                    }
                                    wp.Saved = true;
                                }
                                //trans.Commit();
                            }
                        }
                    }

                    using (MySqlCommand cmd = new MySqlCommand(string.Format("update counter set geocache={0}, log={1}, waypoint={2}, logimage={3}", _geocachesInDB.Count, _logsInDB.Count, _wptsInDB.Count, _logimgsInDB.Count), dbcon))
                        cmd.ExecuteNonQuery();
                }
                else
                {
                    result = false;
                }
            }
            return result;
        }
Exemplo n.º 7
0
 /// <summary>
 /// SQLインジェクション対策。Paramに入力された不正な値をエスケープする。
 /// </summary>
 /// <param name="com">Mysqlコマンド文</param>
 /// <param name="ParameterName">プレースホルダ</param>
 /// <param name="type">データの型</param>
 /// <param name="value">エスケープしたい対象</param>
 public void AddMysqlParameter(
     MySqlCommand com,string ParameterName,MySqlDbType type,Object value)
 {
     MySqlParameter param = com.CreateParameter();
     param.ParameterName = ParameterName;
     param.MySqlDbType = type;
     param.Direction = ParameterDirection.Input;
     param.Value = value;
     com.Parameters.Add(param);
 }
        public void PreparedReader()
        {
            if (Version < new Version(5, 0)) return;

            execSQL("CREATE TABLE  Test (id int(10) unsigned NOT NULL default '0', " +
                 "val int(10) unsigned default NULL, PRIMARY KEY (id)) " +
                 "ENGINE=InnoDB DEFAULT CHARSET=utf8");
            execSQL("CREATE PROCEDURE spTest (IN pp INTEGER) " +
                      "select * from Test where id > pp ");

            MySqlCommand c = new MySqlCommand("spTest", conn);
            c.CommandType = CommandType.StoredProcedure;
            IDataParameter p = c.CreateParameter();
            p.ParameterName = "?pp";
            p.Value = 10;
            c.Parameters.Add(p);
            c.Prepare();
            using (MySqlDataReader reader = c.ExecuteReader())
            {
                while (reader.Read())
                {

                }
            }
        }
        public void UsingUInt64AsParam()
        {
            if (Version < new Version(5, 0)) return;

            execSQL(@"CREATE TABLE Test(f1 bigint(20) unsigned NOT NULL,
                      PRIMARY KEY(f1)) ENGINE=InnoDB DEFAULT CHARSET=utf8");

            execSQL(@"CREATE PROCEDURE spTest(in _val bigint unsigned)
                      BEGIN insert into  Test set f1=_val; END");

            DbCommand cmd = new MySqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "spTest";
            DbParameter param = cmd.CreateParameter();
            param.DbType = DbType.UInt64;
            param.Direction = ParameterDirection.Input;
            param.ParameterName = "?_val";
            ulong bigval = long.MaxValue;
            bigval += 1000;
            param.Value = bigval;
            cmd.Parameters.Add(param);
            cmd.ExecuteNonQuery();
        }
Exemplo n.º 10
0
        public void PreparedReader()
        {
            if (version < new Version(5, 0)) return;

            execSQL("DROP TABLE IF EXISTS Test");
            execSQL("CREATE TABLE  Test (id int(10) unsigned NOT NULL default '0', " +
                 "val int(10) unsigned default NULL, PRIMARY KEY (id)) " +
                 "ENGINE=InnoDB DEFAULT CHARSET=utf8");
            execSQL("CREATE PROCEDURE spTest (IN pp INTEGER) " +
                      "select * from Test where id > pp ");

            MySqlCommand c = new MySqlCommand("spTest", conn);
            c.CommandType = CommandType.StoredProcedure;
            IDataParameter p = c.CreateParameter();
            p.ParameterName = "?pp";
            p.Value = 10;
            c.Parameters.Add(p);
            c.Prepare();
            MySqlDataReader reader = null;
            try
            {
                reader = c.ExecuteReader();
                while (reader.Read())
                {

                }
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }
        }
    public void UnTypedParameterBeingReused()
    {
      MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id, dt) VALUES (?id, ?dt)", conn);
      cmd.Parameters.AddWithValue("?id", 1);
      MySqlParameter p = cmd.CreateParameter();
      p.ParameterName = "?dt";
      p.Value = DBNull.Value;
      cmd.Parameters.Add(p);
      cmd.ExecuteNonQuery();

      cmd.Parameters[0].Value = 2;
      p.Value = DateTime.Now;
      cmd.ExecuteNonQuery();

      cmd.CommandText = "SELECT * FROM Test";
      cmd.Parameters.Clear();
      using (MySqlDataReader reader = cmd.ExecuteReader())
      {
        reader.Read();
        Assert.IsTrue(reader.IsDBNull(2));
        reader.Read();
        Assert.IsFalse(reader.IsDBNull(2));
        Assert.IsFalse(reader.Read());
      }
    }
Exemplo n.º 12
0
        private static void AdicionarParamatros(MySqlCommand cmdComando, Dictionary<string, object> parametros)
        {
            if (parametros == null)
                return;

            foreach (var item in parametros)
            {
                var parametro = cmdComando.CreateParameter();
                parametro.ParameterName = item.Key;
                parametro.Value = item.Value ?? DBNull.Value;
                cmdComando.Parameters.Add(parametro);
            }
        }