C# - 数据集(在多个表中插入/更新)

发布于 2024-12-22 16:06:49 字数 4914 浏览 2 评论 0原文

我不知道如何很好地处理DataSet(以前在VB中使用RecordSet),所以我做了一个看起来很混乱的方法。想知道哪种是使用 DataSet 的正确方法。

我想解决的问题:

  • 真的有必要使用2个DataAdapter、DataSet实例吗?
  • 提交更改的正确方法(在添加行时工作,而不是在更新时工作)
  • 我应该在finally块中处理什么?

感谢您的关注。

代码很长,因为有一些循环和一致性,但令我困惑的是使用数据集编辑或插入行。

public bool SaveData()
{
    bool resp = false;
    this.pObs = null;
    bool editing = false;

    //StringBuilder stringBuilder;    
    string sqlQuery = "SELECT * FROM BooksTemp";
    string sqlQuery2 = "SELECT * FROM Categories;";    

    using (SqlConnection sqlConnection = new SqlConnection(connectionString))
    {
        SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlQuery, connectionString);
        SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);

        SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter(sqlQuery2, connectionString);
        SqlCommandBuilder sqlCommandBuilder2 = new SqlCommandBuilder(sqlDataAdapter2);
        DataSet dataSet2 = new DataSet();

        DataSet dataSet = new DataSet();
        DataTable dataTable = null;
        DataRow Row = null;

        try
        {
            sqlDataAdapter.Fill(dataSet, "BooksTemp");
            dataTable = dataSet.Tables["BooksTemp"];

            sqlDataAdapter2.Fill(dataSet2, "Categories");
            DataTable tableCategorias = dataSet2.Tables["Categories"];

            int i = 0;
            foreach (Ebook ebook in pListEbooks)
            {
                editing = false;

                #region loop_categories

                /* Loop all book categories before save in temporary book table*/
                string codCategorias = null;
                if (ebook.categories != null)
                {
                    bool aux;
                    string catID;

                    try
                    {
                        foreach (Categorias categoria in ebook.categories)
                        {
                            aux = false;
                            /* Search the categorie in DB */
                            if(tableCategorias.Select("CDD = '" + categoria.code + "'").Length > 0)
                                aux = true;

                            /* Include categorie in DB */
                            if (!aux)
                            {
                                /* Generate an ID */
                                catID = Strings.Codify();

                                //tableCategorias.Rows.Find(catID) didnt work
                                while (tableCategorias.Select("ID = '" + catID + "'").Length > 0)
                                {
                                    catID = Strings.Codifica();
                                }
                                Row = tableCategorias.NewRow();
                                Row.BeginEdit();

                                Row["ID"] = catID;
                                Row["Nome"] = categoria.description;

                                tableCategorias.Rows.Add(Row);
                                sqlDataAdapter2.Update(tableCategorias);
                            }
                        }
                    }
                    catch { }
                    finally 
                    {
                        // Shoud I dispose or close something here?
                    }
                }

                #endregion

                /* Verify if the book already have changes in DB */                
                if (dataTable.Select("DistribuidorLivroID = '" + ebook.id + "'").Length == 1)
                {
                    /* Edit row with new ebook changes */
                    editing = true;
                    Row = dataTable.Rows[i];
                    Row.BeginEdit();
                    Row["UpdatedOn"] = DateTime.Now;
                }
                else
                {
                    /* Add new row with ebook changes */
                    Row = dataTable.NewRow();
                    Row.BeginEdit();
                    Row["CreatedOn"] = DateTime.Now;
                }
                Row["DistribuidorLivroID"] = ebook.id;

                if (ebook.price != null)
                    Row["Price"] = ebook.price;
                if (ebook.sorting_title != null)
                    Row["Title"] = ebook.title;
                if (ebook.cover_image != null)
                    Row["Foto"] = ebook.cover_image;

                if (!editing)
                    dataTable.Rows.Add(Row);
                // else
                //     Row.AcceptChanges();

                // Commiting only when I add new row and not when I edit a row
                sqlDataAdapter.Update(dataTable);
                i++;
            }
        }
        catch { }
        finally
        {
            // What should I dispose here?            
        }
    }
    return resp;
}

I dont know how to handle with DataSet very well (used to work with RecordSet in VB) so I made a method that looks very messy. Wondering which is the correct way to use DataSet.

Problems I would like to solve:

  • Is really necessary use 2 instances of DataAdapter, DataSet..?
  • Correct way to commit changes (working when add rows and not when update)
  • What should I dispose in finally blocks?

Thanks for attention.

Code is long because there are some loopings and consistences but what is confusing me is Editing or Insert rows using DataSet.

public bool SaveData()
{
    bool resp = false;
    this.pObs = null;
    bool editing = false;

    //StringBuilder stringBuilder;    
    string sqlQuery = "SELECT * FROM BooksTemp";
    string sqlQuery2 = "SELECT * FROM Categories;";    

    using (SqlConnection sqlConnection = new SqlConnection(connectionString))
    {
        SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlQuery, connectionString);
        SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);

        SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter(sqlQuery2, connectionString);
        SqlCommandBuilder sqlCommandBuilder2 = new SqlCommandBuilder(sqlDataAdapter2);
        DataSet dataSet2 = new DataSet();

        DataSet dataSet = new DataSet();
        DataTable dataTable = null;
        DataRow Row = null;

        try
        {
            sqlDataAdapter.Fill(dataSet, "BooksTemp");
            dataTable = dataSet.Tables["BooksTemp"];

            sqlDataAdapter2.Fill(dataSet2, "Categories");
            DataTable tableCategorias = dataSet2.Tables["Categories"];

            int i = 0;
            foreach (Ebook ebook in pListEbooks)
            {
                editing = false;

                #region loop_categories

                /* Loop all book categories before save in temporary book table*/
                string codCategorias = null;
                if (ebook.categories != null)
                {
                    bool aux;
                    string catID;

                    try
                    {
                        foreach (Categorias categoria in ebook.categories)
                        {
                            aux = false;
                            /* Search the categorie in DB */
                            if(tableCategorias.Select("CDD = '" + categoria.code + "'").Length > 0)
                                aux = true;

                            /* Include categorie in DB */
                            if (!aux)
                            {
                                /* Generate an ID */
                                catID = Strings.Codify();

                                //tableCategorias.Rows.Find(catID) didnt work
                                while (tableCategorias.Select("ID = '" + catID + "'").Length > 0)
                                {
                                    catID = Strings.Codifica();
                                }
                                Row = tableCategorias.NewRow();
                                Row.BeginEdit();

                                Row["ID"] = catID;
                                Row["Nome"] = categoria.description;

                                tableCategorias.Rows.Add(Row);
                                sqlDataAdapter2.Update(tableCategorias);
                            }
                        }
                    }
                    catch { }
                    finally 
                    {
                        // Shoud I dispose or close something here?
                    }
                }

                #endregion

                /* Verify if the book already have changes in DB */                
                if (dataTable.Select("DistribuidorLivroID = '" + ebook.id + "'").Length == 1)
                {
                    /* Edit row with new ebook changes */
                    editing = true;
                    Row = dataTable.Rows[i];
                    Row.BeginEdit();
                    Row["UpdatedOn"] = DateTime.Now;
                }
                else
                {
                    /* Add new row with ebook changes */
                    Row = dataTable.NewRow();
                    Row.BeginEdit();
                    Row["CreatedOn"] = DateTime.Now;
                }
                Row["DistribuidorLivroID"] = ebook.id;

                if (ebook.price != null)
                    Row["Price"] = ebook.price;
                if (ebook.sorting_title != null)
                    Row["Title"] = ebook.title;
                if (ebook.cover_image != null)
                    Row["Foto"] = ebook.cover_image;

                if (!editing)
                    dataTable.Rows.Add(Row);
                // else
                //     Row.AcceptChanges();

                // Commiting only when I add new row and not when I edit a row
                sqlDataAdapter.Update(dataTable);
                i++;
            }
        }
        catch { }
        finally
        {
            // What should I dispose here?            
        }
    }
    return resp;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏末染殇 2024-12-29 16:06:49

我建议您使用类型化数据集。这些将解决您的所有问题并提高代码质量。

I suggest you to use typed Datasets. These will solve all your problems and will improve the code quality.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文