C#将数据添加到SQL Server(如果不存在),如果存在更新计数

我有一些与此代码的问题。我正在尝试编写一个从文本框中读取文本并将单词逐字添加到数据库的代码。如果词已存在于数据库中,则应增加该词添加到数据库中的次数,如果该词不存在,则应将其添加到数据库中。


一切都可以完美地正常运行,但是当我输入数据库中存在的单词和新单词的同时,就会出现问题。代码会按原样增加现有单词的计数,但不会在数据库中添加新单词。而且我没有任何错误。


如何确保新词和旧词的两个功能都相同?


SqlConnection con = new SqlConnection(ConStr);

con.Open();


if (con.State == System.Data.ConnectionState.Open)

{

    string raw = rawtxt.Text.ToString();

    string[] rawwords = raw.Split(' ');


    foreach (var rawword in rawwords)

    {

        string mon_s = "Select * From Dict";

        SqlCommand mon_search = new SqlCommand(mon_s, con);

        SqlDataReader srd = mon_search.ExecuteReader();


        while (srd.Read())

        {

            if (srd[1].ToString() == rawword)

            {

                flag = true;

                break;

            }

        }


        srd.Close();


        if (flag == false)

        {

            string raw_lat_c = rawword.Replace("а", "a").Replace("б", "b").Replace("в", "v").Replace("г", "g").Replace("д", "d").Replace("е", "e").Replace("ё", "e").Replace("ж", "j").Replace("з", "z").Replace("и", "i").Replace("й", "i").Replace("к", "k").Replace("л", "l").Replace("м", "m").Replace("н", "n").Replace("о", "o").Replace("ө", "u").Replace("п", "p").Replace("р", "r").Replace("с", "s").Replace("т", "t").Replace("у", "u").Replace("ү", "u").Replace("ф", "f").Replace("х", "h").Replace("ц", "ts").Replace("ч", "ch").Replace("ш", "sh").Replace("щ", "sh").Replace("ъ", "i").Replace("ы", "i").Replace("ь", "i").Replace("э", "e").Replace("ю", "yu").Replace("я", "ya");


            int count = 1;


            string ins = "Insert into Dict (mongol, latin, count) values(N'" + rawword + "','"+ raw_lat_c +"', '" + count + "')";                      


            SqlCommand command_ins = new SqlCommand(ins, con);

            command_ins.ExecuteNonQuery();

        }


慕斯王
浏览 432回答 2
2回答

神不在的星期二

像这样更改您的代码 if (srd[1].ToString() == rawword) {       flag = true;       break; } else {       flag = false; }
打开App,查看更多内容
随时随地看视频慕课网APP