【问题标题】:Connecting to a database based on a course I follow根据我遵循的课程连接到数据库
【发布时间】:2015-11-13 20:52:07
【问题描述】:

我正在学习一个在线课程,在课程中他们解释了如何从数据库中检索数据。创建连接和命令由DbProviderFactories 类完成。我了解课程中的代码,但是否使用using 进行必要的连接、命令和阅读器?另外,是否有必要进行空检查?代码看起来很杂乱,如果您的数据库中有很多模型(大陆、国家、货币……),则需要大量复制/粘贴,这很糟糕吗?

所以问题真的是,下面的代码是好是坏,还有哪些可以改进的地方?目标是使用 SQLite 作为数据库提供者。这适用于以下方法吗?

public static ObservableCollection<Continent> GetContinents()
{
    var continents = new ObservableCollection<Continent>();
    var provider = ConfigurationManager.ConnectionStrings["DbConnection"].ProviderName;
    var connectionString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;

    using (var connection = DbProviderFactories.GetFactory(provider).CreateConnection())
    {
        if (connection == null) return null;

        connection.ConnectionString = connectionString;
        connection.Open();

        using (var command = DbProviderFactories.GetFactory(provider).CreateCommand())
        {
            if (command == null) return null;

            command.CommandType = CommandType.Text;
            command.Connection = connection;
            command.CommandText = "SELECT * FROM Continent";

            using (var reader = command.ExecuteReader())
                while (reader.Read())
                    continents.Add(new Continent(reader["Code"].ToString(), reader["EnglishName"].ToString()));
        }
    }

    return continents;
}

【问题讨论】:

  • 你为什么认为它需要大量的复制粘贴。首先你的 CommandText 应该作为变量/参数传递给你决定code for re-use的任何方法@更改方法签名处理诸如 SqlCommand、SqlParameter 等的事情。 using 语句用于自动处理对象,请尝试使用 MSDN 并对您的目标进行更多研究,以便您可以了解在线课程之外的事情是如何工作的现实世界。
  • 还有更简单的方法可以在您自己的自定义 DBUtils 类中执行您想要执行的操作..
  • 你可以在这里消除while循环并使用DataAdapter.FIll()方法将内容返回到DataTable你的代码需要一些严肃的Re-Factoring

标签: c# sqlite database-connection factory using


【解决方案1】:

使用 using 连接、命令和阅读器有必要吗?

是的。 这里我注释了代码

using (var command = DbProviderFactories.GetFactory(provider).CreateCommand()) // here you've created the command
            {
                if (command == null) return null;

                command.CommandType = CommandType.Text;
                command.Connection = connection;
                command.CommandText = "SELECT * FROM Continent";

                using (var reader = command.ExecuteReader()) //Here you're reading what the command returned.
                    while (reader.Read())
                        continents.Add(new Continent(reader["Code"].ToString(), reader["EnglishName"].ToString()));
            }

另外,是否有必要进行空检查?

它可以返回空数据,所以绝对是的

代码看起来很混乱

这就是程序员的一生。对对象使用循环将节省空间。

【讨论】:

  • 您在此处以NON Answer 发布的内容的目的是什么,在我看来,复制他的代码并没有真正的帮助,cmets 可以解释这不是重新发布笨重的代码
  • @MethodMan 滚动到右边的家伙。我做了cmets。请 +1 以弥补您的误解:p
猜你喜欢
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-03
  • 2013-02-14
  • 2016-08-05
  • 2012-09-27
相关资源
最近更新 更多