C#Mysql将行移动到另一个表并获取单元格的最大值

时间:2017-07-07 21:03:27

标签: c# mysql row move

我有一个方法可以将一行从一个表移到另一个表。这本身很好。我现在要做的是选择Callbacks表中单元格的最高值。这就是我的尝试:

public static void MoveLead(RadGridView Gridview, RadDropDownList SegmentDropdown, string UniqueID)
{
    try
    {
        string Table = SegmentDropdown.Text;
        using (MySqlConnection cn = new MySqlConnection(Varribles.ConString))
        {
            string query = "BEGIN;  select max(UniqueID) from Callbacks;     INSERT INTO Callbacks select * from " + Table + " where UniqueID = " + UniqueID + "; DELETE FROM " + Table + " where UniqueID = " + UniqueID + "; COMMIT;";
            cn.Open();
            using (MySqlCommand cmd = new MySqlCommand(query, cn))
            {
                cmd.CommandText = query;
                cmd.ExecuteNonQuery();

                Console.WriteLine("query" + Convert.ToInt32(cmd.ExecuteScalar()));
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

提前致谢

2 个答案:

答案 0 :(得分:1)

您是否尝试过更改代码?

public static void MoveLead(RadGridView Gridview, RadDropDownList SegmentDropdown, string UniqueID)
{
    try
    {
        string Table = SegmentDropdown.Text;
        using (MySqlConnection cn = new MySqlConnection(Varribles.ConString))
        {
            cn.Open();

            string query = "select max(UniqueID) from Callbacks;";
            using (MySqlCommand cmd = new MySqlCommand(query, cn))
            {
                // Notice I removed the command text, you are already setting the command text in the constructor for the MySqlCommand
                int UID = Int32.Parse(cmd.ExecuteScalar());

                Console.WriteLine("query" + UID);
            }

            query = "BEGIN;  INSERT INTO Callbacks select * from " + Table + " where UniqueID = ?UniqueID; DELETE FROM " + Table + " where UniqueID = ?UniqueID; COMMIT;";
            using (MySqlCommand cmd = new MySqlCommand(query, cn))
            {
                // Use parameters to sanitize input. There are very rare circumstances where you would want to do a direct concatenation to a query as its susceptible to sql injection
                cmd.Parameters.Add(new MySqlParameter("UniqueID", UniqueID))
                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

另外,我强烈建议您阅读SQL注入。您构建查询的方式很可怕,具体取决于“Table”和“UniqueID”的来源。看到Table变量无法参数化,您需要特别注意填充该值的位置。 查看https://stackoverflow.com/a/652999/5947241& https://dev.mysql.com/doc/connector-net/en/connector-net-programming-prepared-preparing.html

答案 1 :(得分:0)

您正在执行命令两次 - 使用" ExecuteNonQuery"和" ExecuteReader"。 只需删除" cmd.ExecuteNonQuery()"你完成了。