简体   繁体   中英

How to assign a mysql query result to a variable C#

**Hello everyone, im fairly new with c# and am currently trying to make flappy bird in c# windows form application. I am trying to make a leaderboard. I want to save the highscores into a mysql database. But i dont know how to compare the score you get in game with the data in the database. The query works but i dont know how to get that result and assign that to the variable "lastleaderboardscore". Would you guys be able to help?

Thank you**

public partial class Form1 : Form
{
    
   

    int pipeSpeed = 8;
    int groundspeed;
    int gravity = 8;
    int score = 0;
    int lives = 3;
    int totalScore = 0;
    private int tableOf = 5; //preset for the table of 5
    int lastleaderboardscore;
    int i;


    Random rndHeight = new Random();



    {

        InitializeComponent();

        string server = "localhost";
        string database = "flappyLeader";
        string dbUsername = "root";
        string dbPassword = "";
        string connectionString = "SERVER=" + server + ";" + "DATABASE=" +

            database + ";" + "UID=" + dbUsername + ";" + "PASSWORD=" + dbPassword + ";";

        MySqlConnection mysqlcon = new MySqlConnection(connectionString);

        i = 0;
        mysqlcon.Open();
        MySqlCommand cmd = mysqlcon.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "Select score from leaderboard order by Score  desc limit 1 offset 9";
        DataTable dtbl = new DataTable();
        MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        sda.Fill(ds);
        i = Convert.ToInt32(dtbl.Rows.Count.ToString());
        lastleaderboardscore = ds.Tables[0].Rows[2].; 
        
        
        
        mysqlcon.Close();

Here you'll find the code where I compare the 2 variables "totalscore" (score in game) and "lastleaderboardscore"

 if (lives == 0)
        {
            if (totalScore >  lastleaderboardscore)
            {
                /* TextBox1.Show();*/

            }
            label4.Show();
            label4.Text = "your total score is" + totalScore.ToString();
            lives = 3;
            
            pipeSpeed = 8;
            label1.Text = "game Over";
            totalScore = 0;
            label3.Visible = false;

        }

You can use datatable itself to get the result.

SqlCommand command = new SqlCommand(""Select score from leaderboard order by Score  desc limit 1 offset 9", mysqlcon);
DataTable dtbl = new DataTable();
MySqlDataAdapter sda = new MySqlDataAdapter(command);
sda.Fill(dtbl);

lastleaderboardscore =dtbl.Rows(0).Item(0).ToString

This is the basic idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM