简体   繁体   English

如何通过数据库更新制作“得分记录”?

[英]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? 仅使用SQL功能如何实现它? 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: 可以基于参数注入以c#代码实现:

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 . 您可以在ado.net教程中了解更多示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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