检查是否存在记录

时间:2013-04-26 02:37:47

标签: c# sql

有没有人知道如何在运行时只将数据插入数据库一次?因为每当我运行我的系统时,数据将始终插入数据库。它有没有办法只插入一次数据,即使我多次运行程序?这是我的代码

 public async void getUserName()
    {
        LiveConnectClient client = new LiveConnectClient(session);
        LiveOperationResult operationResultUserID = await client.GetAsync("me");
        dynamic resultUserID = operationResultUserID.Result;

        userID = resultUserID.id;
        //getUserInfo();

        Service1Client client1 = new Service1Client();
        name = await client1.RetrieveNameAsync(userID);
        dob = await client1.RetrieveDOBAsync(userID);
        aboutMe = await client1.RetrieveAboutMeAsync(userID);
        country = await client1.RetrieveCountryAsync(userID);
        email = await client1.RetrieveEmailAddressAsync(userID);
        gender = await client1.RetrieveGenderAsync(userID);
        //status = await client1.RetrieveUserStatusAsync(userID);
        UserImage = await client1.RetrieveUserImgAsync(userID);
        vote = await client1.retrieveVotesAsync(userID);
        count = await client1.retrievecountLearningstoryAsync(userID);


        txtAboutmeDisplay.Text = aboutMe;
        txtCountryDisplay.Text = country;
        txtDOBDisplay.Text = dob;
        txtEmailDisplay.Text = email;
        txtGenderDisplay.Text = gender;
        txtName.Text = name;
        txtvotes.Text = vote;
        txtCountDisplay.Text = count.ToString();

        int numberofvotes = int.Parse(txtvotes.Text);
        if (numberofvotes >=1000)
        {
            txtstars.Text = "Gold";
        }
        else if (numberofvotes >= 700)
        {
            txtstars.Text = "Silver";
        }
        else if (numberofvotes >= 500)
        {
            txtstars.Text = "Bronze";
        }



            //txtstars.Visibility == false;
        InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
        DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
        writer.WriteBytes(UserImage);
        await writer.StoreAsync();
        // Create bitmap image
        BitmapImage b = new BitmapImage();
        b.SetSource(randomAccessStream);
        // Update Image on XAML Page

        imgProfilePic.Source = b;

        int countstory = int.Parse(txtCountDisplay.Text);
        if (countstory >= 7)
        {
            achievement = await client1.updateachievementAsync(userID, "wisemen");
        }

        else if (countstory == 6)
        {
            achievement = await client1.updateachievementAsync(userID, "Smartboy");
        }
        else if (countstory == 5)
        {
            achievement = await client1.insertAchievementAsync(userID, "novice");
        }

    }

我的网络服务代码

 public string insertAchievement(string userid, string achievements)
    {
        SqlConnection con = new SqlConnection(connectionString);

        con.Open();
        string insertInterBadges = "Insert into [Achievement] (UserID, Achievement) VALUES " + " (@userid,@achievements)";
        SqlCommand cmd = new SqlCommand(insertInterBadges, con);
        cmd.Parameters.AddWithValue("@userId", userid);
        cmd.Parameters.AddWithValue("@achievements", achievements);

        int check = cmd.ExecuteNonQuery();
        con.Close();
        if (check > 0)
        {
            return "Success";
        }
        else
        {
            return "Fail";
        }
    }


    public string updateachievements(string userid, string achievements)
    {
        SqlConnection con = new SqlConnection(connectionString);

        con.Open();
        string updateAchievements = "UPDATE Achievement SET Achievement=@achievement Where UserID=@userid";
        SqlCommand cmd = new SqlCommand(updateAchievements, con);
        cmd.Parameters.AddWithValue("@userId", userid);
        cmd.Parameters.AddWithValue("@achievement", achievements);

        int check = cmd.ExecuteNonQuery();
        con.Close();
        if (check > 0)
        {
            return "Success";
        }
        else
        {
            return "Fail";
        }

    }

我的reference.cs

 [System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IService1/updateachievement", ReplyAction = "http://tempuri.org/IService1/updateachievement")]
    System.Threading.Tasks.Task<string> updateachievementAsync(string userId, string achievements);

    [System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IService1/insertAchievement", ReplyAction = "http://tempuri.org/IService1/insertAchievement")]
    System.Threading.Tasks.Task<string> insertAchievementAsync(string userId, string achievements);

 public System.Threading.Tasks.Task<string> updateachievementAsync(string userId, string achievements)
    {
        return base.Channel.insertAchievementAsync(userId, achievements);
    }

    public System.Threading.Tasks.Task <string> insertAchievementAsync(string userId, string achievements)
    {
        return base.Channel.insertAchievementAsync(userId, achievements);
    }

我正在使用webservice

1 个答案:

答案 0 :(得分:1)

通过代码的外观,特别是UPDATE语句,只能为单个用户分配一个成就。这种限制使得在UserId, AcheivementId上创建唯一索引的简单方法不是一个可行的选项(此索引,如果创建,将通过SQL插入错误防止重复条目)。

另一种更正确的解决方案是在插入之前查询表以查看值是否已存在:

SELECT COUNT(*) FROM Achievement WHERE UserId = @userId AND Achievement = @achievement

这可以在以下块中使用:

using (SqlConnection conn = new SqlConnection(connectionString)) {
    conn.Open();
    bool isNewValue = true;
    using (SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM Achievement WHERE UserId = @userId AND Achievement = @achievement")) {
        cmd.Parameters.AddWithValue("@userId", userid);
        cmd.Parameters.AddWithValue("@achievement", achievements);
        isNewValue = ((int)cmd.ExecuteScalar() == 0);
    }

    if (isNewValue) {
        // insert user achievement / etc
    }
}