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

时间:2018-05-05 07:02:35

标签: 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();
        }

        if (flag == true)
        {
            string upd_count = "Update Dict Set count=count+1 Where mongol=N'" + rawword + "'";
            SqlCommand command_upcnt = new SqlCommand(upd_count, con);
            command_upcnt.ExecuteNonQuery();                        
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您必须在每个foreach语句中重置“flag”的值。所以,在此之前,您应该添加Sub ChangeSource() Dim i As Long With ActiveDocument For i = .InlineShapes.Count To 1 Step -1 With .InlineShapes(i) If Not .LinkFormat Is Nothing Then With .LinkFormat .SourceFullName = Replace(.SourceFullName, .SourcePath, "C:\NewPath\") End With End If End With Next i End With End Sub - 就像这样:

SqlDataReader srd = mon_search.ExecuteReader();

你现在正在做的是,一旦在你的数据库中找到“rawwords”中的一个单词,所有剩余的单词将永远“重复”,因为你的标志将是假的。

答案 1 :(得分:0)

更改您的代码,例如This

 if (srd[1].ToString() == rawword)
 {
       flag = true;
       break;
 }
 else
 {
       flag = false;
 }