【问题标题】:Insert data to sqlite from json array - UWP将数据从 json 数组插入到 sqlite - UWP
【发布时间】:2018-05-04 14:08:02
【问题描述】:

我已将 json 数组值存储到一个类中,并使用以下代码对其进行反序列化。如何将该 json 数据插入到 sqlite?

[{"ID":1,"name":"Shyam","class":"a"},{"ID":2,"name":"Bran","class":"b"}]

 using Newtonsoft.Json;
 using SQLitePCL;

 var StudentJSON = await response.Content.ReadAsStringAsync();
 var jsonData = JsonConvert.DeserializeObject<List<StudentClass>>(StudentJSON);
 using (var connection = new SQLiteConnection(Windows.Storage.ApplicationData.Current.LocalFolder.Path + "\\Student_DB.sqlite"))
                {
                    using (var statement = connection.Prepare(@"INSERT INTO Student (ID,name,class)
                                VALUES(?, ?,?);"))
                    {
                        // Inserts data.
                    }
                }

【问题讨论】:

    标签: json sqlite uwp


    【解决方案1】:

    使用“SQLite.Net”,您可以将数据插入到 sqlite 表中,

    // Insert the new student record in the Student table.  
    
    string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "StudentDb.sqlite");
    
    public void Insert(Student std)  
    {  
        using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), dbPath))  
        {  
             conn.RunInTransaction(() =>  
              {  
                  conn.Insert(std);  
               });  
        }  
    }  
    

    【讨论】:

    • 显示错误:SQLite.Net.NotNullConstraintViolationException: 'NOT NULL constraint failed: Student.ID'
    • 看来你可能忘记设置Student.ID字段(不允许为NULL)
    猜你喜欢
    • 2012-05-22
    • 2013-02-05
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    相关资源
    最近更新 更多