2017-04-11 70 views
0

我基本上建立一個多選題測驗,其中用戶將根據他們的表現等得到一個分數... 我將他們的分數保存到每個單獨的不同測試的數據庫上我的網站。如果他們在多項選擇測試的特定階段收到的分數小於數據庫中已分配的值,我不想保存它們的分數。我需要能夠提取數據庫中當前用戶的分數(我的數據庫表中默認分數爲0,因此總會有一個值),將它與剛剛收到的分數進行比較,如果分數更大,則保存新的分數進入數據庫。從MySql數據庫收集數據來比較變量

我無法解決如何提取用戶評分並將其分配給變量,以便我可以比較兩者。我現在用的用戶ID作爲表的主鍵

到目前爲止,我有如下因素:

protected void Submit_Click(object sender, EventArgs e) 
{ 
    if (!this.IsValid) 
     return; 
    int score = 0; 
    List<RadioButtonList> list = new List<RadioButtonList>() { RadioButtonList1, RadioButtonList2, RadioButtonList3, RadioButtonList4, RadioButtonList5, RadioButtonList6, RadioButtonList7, RadioButtonList8, RadioButtonList9, RadioButtonList10 }; 
    foreach (var element in list) 
    { 
     if (element.SelectedValue == "Correct") 
     { 
      score++; 
     } 

    } 
    Response.Write("you scored: " + score); 
    Button1.Visible = false; 

    if (score != 0) ; 
    { 
     string UserId = User.Identity.GetUserId(); 

     string MyConString = "SERVER=localhost;" + 
     "DATABASE=synther_physics;" + 
     "UID=root;" + 
     "PASSWORD=rootpass;"; 
     MySqlConnection connection = new MySqlConnection(MyConString); 




     MySqlCommand commandPull = connection.CreateCommand(); 
     commandPull.CommandText = "SELECT score FROM userscores WHERE Id = UserID"; 
     int DBscore = 
     connection.Open(); 
     int RowsAffected = commandPull.ExecuteNonQuery(); 
     connection.Close(); 



     if (DBscore < score) ; 
     { 
      Response.Write("New high score! Well done!"); 
      MySqlCommand commandReplace = connection.CreateCommand(); 
      commandReplace.CommandText = "REPLACE INTO userscores (Id, momentsandenergytestscore) VALUES (@Id,@score)"; 

      commandReplace.Parameters.AddWithValue("@Id", UserId); 
      commandReplace.Parameters.AddWithValue("@score", score); 

      connection.Open(); 
      int RowsAffectedReplace = commandReplace.ExecuteNonQuery(); 
      connection.Close(); 

     } 

     else; 
     { 
      Response.Write("You didnt beat your previous best of" + DBscore); 
     } 
    } 
} 

這裏我其實想拉和比較數據的部分是在這裏(注意代碼不完整):

MySqlCommand commandPull = connection.CreateCommand(); 
commandPull.CommandText = "SELECT score FROM userscores WHERE Id = UserID"; 
DBscore = 
connection.Open(); 
int RowsAffected = commandPull.ExecuteNonQuery(); 
connection.Close(); 

回答

0

您可以使用ExecuteScalar來獲得分數:

int dbscore = (int)commandPull.ExecuteScalar(); 

ExecuteScalar執行查詢,並返回查詢返回的結果集中第一行的第一列。

+0

三江源的性反應,我想這個時候得到一個錯誤:對象引用不設置到對象的實例。 –

+0

也許問題在這裏:'commandPull.CommandText =「SELECT score FROM userscores WHERE Id = UserID」;'。你必須爲'@ Id'和'commandPull.Parameters.AddWithValue(「@ Id」,UserId)更改'UserId';' – Pikoh

+0

這是一個新行嗎?在定義變量DBscore之前? –