如果满足语句,则修改数据表列值

时间:2014-08-26 16:01:22

标签: c# sql ado.net

我有一个包含列的数据表:用户名,密码和分数。

我在完成测验(QuizForm)后得分,然后我应该使用用户名和密码登录并保存得分,如果它高于前一个。

我做了这个,但我想这是错的

static public void SaveScore(string username, string score) 
{
    try 
    {
        DatabaseConnection db = new DatabaseConnection();
        db.Connection.Open();

        SqlCommand cmdWrite = db.GetCommand("insert into Users(Username, Password) values(username, password)");
        SqlCommand cmdRead = db.GetCommand("select * from Users");

        SqlDataReader reader = cmdRead.ExecuteReader();
        if (reader.HasRows) {
            while (reader.Read()) {
                if (username == reader["Username"].ToString() && int.Parse(score) > Convert.ToInt32(reader["Score"])) {
                    cmdWrite.Parameters.AddWithValue(@"Score", score);
                }
            }
        }
        db.Connection.Close();


    }
    catch (SqlException ex) {
        MessageBox.Show(ex.Message);
    }
}

它没有保存分数。 任何想法如何解决它?

P.S。 GetCommand看起来像这样:

public SqlCommand GetCommand(string CommandText){
        var cmd = new SqlCommand();
        cmd.Connection = Connection;
        cmd.CommandText = CommandText;
        return cmd;
    }

2 个答案:

答案 0 :(得分:0)

您的cmdWrite不包括分数列:

SqlCommand cmdWrite = db.GetCommand("insert into Users(Username, Password) values(username, password)");

应该是这样的:

SqlCommand cmdWrite = db.GetCommand("insert into Users(Username, Password, Score) values(@username, @password, @score)");

然后:

cmdWrite.Parameters.AddWithValue("@score", score);

答案 1 :(得分:0)

解决了这个问题。

这里是:

static public void SaveScore(string username, string score) {
        try {
            DatabaseConnection db = new DatabaseConnection();
            db.Connection.Open();
            var cmd = db.GetCommand("SELECT Score FROM Users WHERE Username = username");
            var oldScore = Convert.ToInt32(cmd.ExecuteScalar());
            var value = Int32.Parse(score);
            if (oldScore < value) {
                cmd = db.GetCommand("UPDATE Users SET Score = @score WHERE Username = @username AND Score < @score");
                cmd.Parameters.AddWithValue("@score", value);
                cmd.Parameters.AddWithValue("@username", username);
                MessageBox.Show("New High Score Was Saved","Congratulations",MessageBoxButtons.OK);
            }
            else {
                MessageBox.Show("High Score Wasn't Reached. Try Again", "Game Over", MessageBoxButtons.OK);
            }

            cmd.ExecuteNonQuery();
            db.Connection.Close();                
        }
        catch (SqlException ex) {
            MessageBox.Show(ex.Message);
        }
    }