【问题标题】:How do I access a database in C#如何在 C# 中访问数据库
【发布时间】:2010-09-10 13:40:14
【问题描述】:

基本上,我想简要说明如何使用 C# 代码访问 SQL 数据库。我收集到需要连接和命令,但发生了什么?我想我要问的是有人来揭开这个过程的神秘面纱。谢谢。

为了清楚起见,就我而言,我正在做网络应用程序和电子商务。都是 ASP.NET、C# 和 SQL 数据库。

我将继续并关闭此线程。这有点笼统,我将发布一些关于该主题的更有针对性和教程式的问题和答案。

【问题讨论】:

    标签: c# asp.net sql


    【解决方案1】:

    MSDN 有一篇很好的文章:

    http://msdn.microsoft.com/en-us/library/s7ee2dwt(VS.71).aspx

    您应该查看数据读取器以获取简单的选择语句。来自MSDN 页面的示例:

    private static void ReadOrderData(string connectionString)
    {
        string queryString = 
            "SELECT OrderID, CustomerID FROM dbo.Orders;";
        using (SqlConnection connection = new SqlConnection(
                   connectionString))
        {
            SqlCommand command = new SqlCommand(
                queryString, connection);
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            try
            {
                while (reader.Read())
                {
                    Console.WriteLine(String.Format("{0}, {1}",
                        reader[0], reader[1]));
                }
            }
            finally
            {
                // Always call Close when done reading.
                reader.Close();
            }
        }
    }
    

    它基本上首先创建一个SqlConnection 对象,然后创建一个SqlCommand-object 来保存您将要执行的实际选择,以及对我们刚刚创建的连接的引用。然后它打开连接并在下一行执行您的语句并返回一个SqlDataReader 对象。

    然后在 while 循环中输出读取器中第一行的值。每次调用“reader.Read()”时,reader 都会包含一个新行。

    然后关闭阅读器,因为我们正在退出“使用”-secret,连接也被关闭。


    编辑:如果您正在寻找有关在 ASP.NET 中选择/更新数据的信息,4GuysFromRolla 有一个非常好的Multipart Series on ASP.NET 2.0's Data Source Controls

    EDIT2:正如其他人所指出的,如果您使用的是较新版本的 .NET,我建议您查看 LINQ。简介、示例和文章可以在this MSDN page 上找到。

    【讨论】:

    • 如果作用域为当前方法,最好在命令和连接周围使用 using 语句。
    • 我同意,但 MSDN 在初学者文章中似乎不是这样(我从那里复制并粘贴了这个),所以我认为这很好。
    • 我可以看到不遵守“最佳实践”的样本的逻辑,以免混淆。但是恕我直言,处理数据库连接非常重要(尤其是在 Web 应用程序中 - OP 正在谈论 ASP.NET),因此应该始终包含它。继续,更新你的例子:)
    • 在 Linq 退出时学习这种旧方法似乎毫无意义。既然有更快、更简单、更强大的方法,为什么还要学习旧技术?
    【解决方案2】:

    随着 LINQ 的出现,旧的 ADO.Net(sqlConnection 等)是一个恐龙。 LINQ 需要 .Net 3.5,但向后兼容所有 .Net 2.0+ 和 Visual Studio 2005 等。

    从 linq 开始非常简单。

    • 在您的项目中添加一个新项目,一个 linq-to-sql 文件,该文件将放置在您的 App_Code 文件夹中(对于本示例,我们将调用它example.dbml)
    • 从您的服务器资源管理器中,将数据库中的一个表拖到 dbml 中(在本例中,该表将命名为 items
    • 保存 dbml 文件

    您现在已经构建了一些类。您构建了 exampleDataContext 类,它是您的 linq 初始化程序,并且您构建了 item 类,它是 items 表中对象的类。这一切都是自动完成的,您无需担心。现在说我想获得 itemID 为 3 的记录,这就是我需要做的:

    exampleDataContext db = new exampleDataContext(); // initializes your linq-to-sql
    item item_I_want = (from i in db.items where i.itemID == 3 select i).First(); // using the 'item' class your dbml made
    

    仅此而已。现在您有了一个名为 item_I_want 的新 item...现在,如果您想从 item 获取一些信息,您只需像这样称呼它:

    int intID = item_I_want.itemID;
    string itemName = item_I_want.name;
    

    Linq 非常易于使用!而这只是冰山一角。

    当您拥有更强大、更简单的工具时,无需学习过时的 ADO :)

    【讨论】:

      【解决方案3】:

      读起来像是一个初学者的问题。这需要初学者视频演示。

      http://www.asp.net/learn/data-videos/

      他们专注于 ASP.NET,但关注数据库方面。

      【讨论】:

      • 非常初学者的问题,因此标签。感谢您的链接!我喜欢动起来的漂亮图片!
      【解决方案4】:

      要查看的主题:

      1. ADO.NET 基础知识
      2. LINQ to SQL
      3. 托管数据库提供商

      【讨论】:

        【解决方案5】:

        如果它是一个 Web 应用程序,这里有一些很好的资源,可以帮助您开始在 .NET 中进行数据访问:

        http://weblogs.asp.net/scottgu/archive/2007/04/14/working-with-data-in-asp-net-2-0.aspx

        【讨论】:

          【解决方案6】:

          在 SQL 服务器数据库上连接/执行操作:

          using System.Data;
          using System.Data.SqlClient;
          
          string connString = "Data Source=...";
          SqlConnection conn = new SqlConnection(connString); // you can also use ConnectionStringBuilder
          connection.Open();
          
          string sql = "..."; // your SQL query
          SqlCommand command = new SqlCommand(sql, conn);
          
          // if you're interested in reading from a database use one of the following methods
          
          // method 1
          SqlDataReader reader = command.ExecuteReader();
          
          while (reader.Read()) {
              object someValue = reader.GetValue(0); // GetValue takes one parameter -- the column index
          }
          
          // make sure you close the reader when you're done
          reader.Close();
          
          // method 2
          DataTable table;
          SqlDataAdapter adapter = new SqlDataAdapter(command);
          adapter.Fill(table);
          
          // then work with the table as you would normally
          
          // when you're done
          connection.Close();
          

          大多数其他数据库服务器,如 MySQL 和 PostgreSQL,都有类似的连接和操作接口。

          【讨论】:

            【解决方案7】:

            如果您正在寻找易于理解的教程,那么您应该前往 www.ASP.net 网站。

            这里是入门视频页面的链接:http://www.asp.net/learn/videos/video-49.aspx

            如果你想下载,这里是视频:video download

            这里是视频中 C# 项目的链接:download project

            祝你好运。

            【讨论】:

              【解决方案8】:

              我还建议使用数据集。它们非常易于使用,只需点击几下鼠标,无需编写任何代码,对于小型应用程序来说已经足够了。

              【讨论】:

                【解决方案9】:

                如果您有 Visual Studio 2008,我建议您跳过 ADO.NET 并直接使用 LINQ to SQL

                【讨论】:

                  【解决方案10】:

                  @J D OConal 基本上是正确的,但你需要确保你处理掉你的连接:

                  string connString = "Data Source=...";
                  string sql = "..."; // your SQL query
                  
                  //this using block
                  using( SqlConnection conn = new SqlConnection(connString) )
                  using( SqlCommand command = new SqlCommand(sql, conn) )
                  {
                      connection.Open();
                  
                      // if you're interested in reading from a database use one of the following methods
                  
                      // method 1
                      SqlDataReader reader = command.ExecuteReader();
                  
                      while (reader.Read()) {
                          object someValue = reader.GetValue(0); // GetValue takes one parameter -- the column index
                      }
                  
                      // make sure you close the reader when you're done
                      reader.Close();
                  
                      // method 2
                      DataTable table;
                      SqlDataAdapter adapter = new SqlDataAdapter(command);
                      adapter.Fill(table);
                  
                      // then work with the table as you would normally
                  
                      // when you're done
                      connection.Close();
                  }
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2014-04-29
                    • 2011-07-23
                    • 1970-01-01
                    • 2020-07-22
                    • 2017-04-20
                    • 1970-01-01
                    相关资源
                    最近更新 更多