【问题标题】:Persisting changes in dataset to sqlite database将数据集的更改持久化到 sqlite 数据库
【发布时间】:2010-11-22 23:29:44
【问题描述】:

我是 ADO.NET 的新手。我正在努力将数据集中的更改持久化到我的 sqlite 数据库中。

它有一个表“Category”,它有 3 个字段:CategoryID(int)、CategoryName(varchar(100)、Parent(int)。parent 可以为 null。

我正在尝试在我的数据库中插入一个新行。我有以下代码。

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Text;

namespace QS_Optimized
{
    class UsingDataset
    {
        static DataSet dataset;
        static SQLiteConnection conn;

        static UsingDataset()
        {
            conn = new SQLiteConnection("data source = ..\\sqlitedb_amrit.db");
            dataset = new DataSet("MyDataset");
        }

        public static void UpdateFromDB()
        {
            SQLiteDataAdapter sqda = new SQLiteDataAdapter("Select Category.* from Category where Parent = 0", conn);
            sqda.Fill(dataset, "Category");
            //dataset.Tables["Category"].Columns["CategoryID"].AllowDBNull = false;
            //dataset.Tables["Category"].Columns["CategoryName"].AllowDBNull = false;

            // Insert command
            SQLiteCommand cmdInsert = new SQLiteCommand();
            cmdInsert.Connection = conn;
            cmdInsert.CommandText = @"Insert into Category('CategoryID','CategoryName','Parent') values" +
                @"(@id,@name,@parent)";
            cmdInsert.Parameters.Add(new SQLiteParameter("@id",DbType.Int64));
            cmdInsert.Parameters.Add(new SQLiteParameter("@name",DbType.String));
            cmdInsert.Parameters.Add(new SQLiteParameter("@parent",DbType.Int64));
            sqda.InsertCommand = cmdInsert;

            // Add Datarows to dataset;
            DataTable tbl = dataset.Tables["Category"];
            DataRow drw = tbl.NewRow();
            drw[0] = 64;
            drw[1] = "TestCategory";
            drw[2] = 0;
            tbl.Rows.Add(drw);

            sqda.Update(dataset,"Category");
        }

        public static void Main()
        {
            UpdateFromDB();           
        }           
    }
}

当我执行它时,我得到一个异常:

Category.Categoryname 不能为 NULL

。 为什么会出现这个错误?我不认为我在插入空值

另外,当我在该特定列中允许空值(在数据库中完成更改)时,此代码会插入一个新行

(64,NULL,NULL)

进入数据库中的表。我现在表中已经有 63 条记录了

【问题讨论】:

    标签: c# sqlite ado.net


    【解决方案1】:

    保持简单。只需使用 SQLite Command 对象。设置sql为

    插入表名(col1, col2, col3)值(@val1,@val2,@val3)

    然后将值传递到命令对象的参数集合中。这样您就可以更轻松地进行调试,因为您可以在运行时查看每个参数值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-19
      • 2021-09-19
      • 2019-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多