简体   繁体   中英

How can I make 'score record' with database update?

I'm making millionaire game for my university project and i'm stuck in database part. Game asks the player name before game start. So i record to database as name/money. I can record the scores. But I want to change record if player(same name login) finish higher than before. And show this score in a label.(for show to player while he/she playing.) How can I do this? This code is working:

public void skorK()
        {

                    string gelenVeri = skor.veri;
                    string dbConnectionString = ("Data Source=sorular.db;Version=3;");
                    SQLiteConnection sqliteCon = new SQLiteConnection(dbConnectionString);
                    try
                    {
                        sqliteCon.Open();
                        string Query = ("INSERT INTO skor(isim, puanSkor) VALUES ('" + gelenVeri + "', '" + mevcutPara + "')");
                        SQLiteCommand createCommand = new SQLiteCommand(Query, sqliteCon);
                        createCommand.ExecuteNonQuery();

I tried this. But I'm not even sure that it works. I think it does nothing:

string degistir = ("SELECT count(*) FROM skor WHERE isim='" + gelenVeri + "'");
                        SQLiteCommand createCommand2 = new SQLiteCommand(degistir, sqliteCon);
                            int isimDegis = Convert.ToInt32(createCommand2.ExecuteScalar());

                        if (isimDegis > 0)
                        {
                            string degistir2 = ("UPDATE skor SET isim='"+ gelenVeri +"', puanSkor='" + mevcutPara + "'");

                        } 

How about implement it just using SQL power? Full command might looks like something below:

UPDATE skor SET puanSkor=MAX(puanSkor, @newScore) WHERE isim=@yourPlayerName

It can be implemented in c#-code based on parameters injection:

string query = ("UPDATE skor SET puanSkor=MAX(puanSkor, @newScore) WHERE isim=@yourPlayerName");
SQLiteCommand updateHighscroeCommand = new SQLiteCommand(query, sqliteCon);
updateHighscroeCommand.Parameters.AddWithValue("@newScore", mevcutPara);
updateHighscroeCommand.Parameters.AddWithValue("@yourPlayerNam", gelenVeri);
updateHighscroeCommand.ExecuteNonQuery();

Using Parameters collection is a good practice that prevents security problems and makes code bit more structured. You can learn more examples in ado.net tutorials .

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