UWP - 在某些条件下将数据从服务器(json)插入数据库

时间:2018-06-05 05:38:38

标签: c# json database sqlite uwp

我有一个应用程序,用于检查服务器(json)和数据库上的数据。我想当json上的id与数据库中的id不同时,它会将具有不等id的所有数据插入到数据库中。 代码:

var sqlpath = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "ebookstore.db");
            this.DataContextChanged += (s, e1) => { UpdateViewModel = DataContext as ViewModels.UpdateViewModel; };
            string idDb = @"SELECT id FROM books where parent_folder_id = 2 and title like '%guru%'";

            var IDdb = objConnUpdate.Prepare(idDb);
            IDdb.Step();
            iddb = IDdb[0].ToString();
            IDDB = Convert.ToInt32(iddb.ToString());
            ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
            {
                            try
                            {
                                Downloading.IsOpen = true;
                                string urlPath1 = "https://.../fetch/k13G";
                                var httpClient1 = new HttpClient(new HttpClientHandler());
                                httpClient1.DefaultRequestHeaders.TryAddWithoutValidation("KIAT-API-KEY", "...*");
                                var values1 = new List<KeyValuePair<string, string>>
                            {
                                new KeyValuePair<string, string>("halaman", "1"),
                                new KeyValuePair<string, string>("limit", "20"),
                            };

                                var response1 = await httpClient1.PostAsync(urlPath1, new FormUrlEncodedContent(values1));
                                response1.EnsureSuccessStatusCode();

                                string jsonText1 = await response1.Content.ReadAsStringAsync();
                                JsonObject jsonObject1 = JsonObject.Parse(jsonText1);
                                JsonArray jsonData1 = jsonObject1["data"].GetArray();

                                foreach (JsonValue groupValue in jsonData1)
                                {
                                    JsonObject groupObject = groupValue.GetObject();

                                    string ID = groupObject["id"].GetString();

                                    BukuUpdate file1 = new BukuUpdate();
                                    file1.ID = ID;
                                    int intID = Convert.ToInt32(file1.ID);

                                    if (intID != IDDB)
                                    {

                                                string jumlahidDb = @"SELECT COUNT(id) FROM books where parent_folder_id = 2 and id > " + IDDB + " and title like '%guru%'";

                                                var jumlahIdDB = objConnUpdate.Prepare(jumlahidDb);
                                                jumlahIdDB.Step();
                                                if (jumlahiddb < jumlahbuku)
                                                {;
                                                    if (nama == "Kelas_01_SD_")
                                                    {
                                                        DownloadBukuK2013G(url);
                                                        string K2013GUpdate = @"INSERT INTO books (id,title,folder_id,identifier,parent_folder_id) SELECT " + intID + ",'" + namaFile + ".pdf',34,'" + namaFile +
                                                        ".pdf',2 WHERE not exists (select id AND title AND folder_id AND identifier AND parent_folder_id FROM books WHERE id=" + intID + " and title='" + namaFile +
                                                        ".pdf' AND folder_id=34 and identifier='" + namaFile + ".pdf' and parent_folder_id=2)";
                                                        var K2013GQuery = objConnUpdate.Prepare(K2013GUpdate);
                                                        K2013GQuery.Step();
                                                    }

BukuUpdate.cs:

public class BukuUpdate
{
        public string ID { get; set; }
}

数据库: database stucture

我没有成功实施它。如何处理?

1 个答案:

答案 0 :(得分:0)

  

但如果我使用上一篇文章中的代码,它只显示数据库中的第一个id

您通过此代码行iddb = IDdb[0].ToString();获取第一个ID以供使用。实际上id列表保存在idDb变量中。

  

我想如果json上的id与数据库中的id不同,那么数据将被添加到数据库中。如果相同,那么什么都不做。

为此,您可以从数据库中获取所有id,并逐一与Json的新收入记录进行比较。在您的代码段中,我不确定您为Sqlite使用的Nuget软件包是什么,而是使用Microsoft.Data.SQLite软件包的最新官方教程。我还强烈建议您按照official tutorial使用Microsoft.Data.SQLite包。通过这种方式,插入示例代码可能是这样的:

public sealed partial class MainPage : Page
{ 
    private void btngettest_Click(object sender, RoutedEventArgs e)
    {
        List<String> ids = sqlhelp.GetData();
        string idfromjson = "2";
        foreach (string id in ids)
        {
            if (id != idfromjson)
            {
                //do insert operation
            }
            else
            {
                //do nothing
            }
        } 
    } 
}

public class sqlhelp
{
    public static void InitializeDatabase()
    {
       ... 
    }

    public static List<String> GetData()
    {
        List<String> entries = new List<string>();

        using (SqliteConnection db =
            new SqliteConnection("Filename=sqliteSample.db"))
        {
            db.Open();
            SqliteCommand selectCommand = new SqliteCommand
                ("SELECT id from MyTable", db);
            SqliteDataReader query = selectCommand.ExecuteReader();
            while (query.Read())
            {
                entries.Add(query.GetString(0));
            }
            db.Close();
        }
        return entries;
    }

由于您的代码段包含许多您自己的逻辑,因此我没有对原始代码段进行更改。请引用我可能更清楚的简单代码。