2013-04-26 148 views
0

有谁知道如何在运行时只向数据库插入一次数据?因为现在每当我运行我的系统时,数据总会被插入到数据库中。它有什么办法只是插入数据只有一次,即使我已经运行程序多少次?这里是我的代码检查是否存在记录

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"); 
     } 

    } 

我的web服务代码

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 [email protected] Where [email protected]"; 
     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); 
    } 

我使用web服务的方式

+0

的明显的答案是在再次插入数据之前检查数据是否已经存在于数据库中。 – 2013-04-26 02:41:27

回答

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 
    } 
} 
+0

非常感谢它的工作正常! :) – 2013-04-26 12:23:02