在C#中更新数据库命令

时间:2013-07-01 13:08:21

标签: c# mysql .net sql database

        using (MySqlCommand bb = new MySqlCommand("UPDATE  members SET  Begin = 1 WHERE id ='" + uid + "';"))
        {
            bb.Connection = con;
            con.Open();
            using (MySqlCommand fff = new MySqlCommand("UPDATE  members SET  b = 1 WHERE id ='" + uid + "';"))
            {
                fff.Connection = con;
            }
            this.Hide();
            Main main = new Main();
            main.Show();
        }

我正在尝试将两个表,B和Begin更新为当前登录用户(我的uid命令:

  using (MySqlCommand id = new MySqlCommand("SELECT id FROM members WHERE username='" + textBox1.Text + "';"))
                            {
                                id.Connection = con;
                                MySqlDataReader read3 = cmd.ExecuteReader();
                                read3.Dispose();
                                int idd = (int)id.ExecuteScalar();
                                uid = idd;
                                Begin.uid = idd;
                                MySqlDataReader read4 = id.ExecuteReader();
                                read4.Dispose();
                                id.Dispose();
                            }

我不知道为什么,但它没有更新数据库。

2 个答案:

答案 0 :(得分:5)

您没有执行命令。

您需要fff.ExecuteScalar();bb.ExecuteScalar();

ExecuteNonQuery();

此外,您很容易受SQL Injection攻击,请尝试使用paramerterized queries

例如:

 bb.CommandText = "UPDATE members SET  Begin = 1 WHERE id = @id";  
 bb.Parameters.AddWithValue("@id", id);
 bb.ExecuteNonQuery();

答案 1 :(得分:0)

首先是用户参数化查询,其次是您在ExecuteNonQuery()的任何一个上致电SqlCommands

using (MySqlCommand bb = new MySqlCommand("UPDATE  members SET  Begin = 1 WHERE id = @id;"))
{
    bb.Parameters.AddWithValue("@id", uid);
    bb.Connection = con;
    con.Open();

    bb.ExecuteNonQuery();

    using (MySqlCommand fff = new MySqlCommand("UPDATE  members SET  b = 1 WHERE id = @id;"))
    {
        fff.Parameters.AddWithValue("@id", uid);
        fff.Connection = con;

        fff.ExecuteNonQuery();
    }

    this.Hide();
    Main main = new Main();
    main.Show();
}