【问题标题】:Fetch data from the SQL Server using ADO.NET使用 ADO.NET 从 SQL Server 获取数据
【发布时间】:2011-03-15 10:33:03
【问题描述】:

在 SQL Server 2008 中是否有任何教程可以做到这一点? 你有例子吗?

是否可以执行存储过程并在 C# 中获取结果?

【问题讨论】:

  • 我建议先理解这些概念。 ADO.NET 代码与 SQL Server 2005/2008 的工作方式没有区别。这一切都在于 System.Data.SQLClient 命名空间提供了哪些对象,它们之间的关系/不同以及这些对象具有哪些方法。

标签: c# sql sql-server ado.net


【解决方案1】:

SqlDataReader 类是一个很好的起点:

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();

        // Call Read before accessing data.
        while (reader.Read())
        {
            Console.WriteLine(String.Format("{0}, {1}",
                reader[0], reader[1]));
        }

        // Call Close when done reading.
        reader.Close();
    }
}

更具体地说:Using parameters with a SqlCommand and a Stored Procedure

static void GetSalesByCategory(string connectionString, 
    string categoryName)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        // Create the command and set its properties.
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandText = "SalesByCategory";
        command.CommandType = CommandType.StoredProcedure;

        // Add the input parameter and set its properties.
        SqlParameter parameter = new SqlParameter();
        parameter.ParameterName = "@CategoryName";
        parameter.SqlDbType = SqlDbType.NVarChar;
        parameter.Direction = ParameterDirection.Input;
        parameter.Value = categoryName;

        // Add the parameter to the Parameters collection. 
        command.Parameters.Add(parameter);

        // Open the connection and execute the reader.
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();

        if (reader.HasRows)
        {
            while (reader.Read())
            {
                Console.WriteLine("{0}: {1:C}", reader[0], reader[1]);
            }
        }
        else
        {
            Console.WriteLine("No rows found.");
        }
        reader.Close();
    }
}

【讨论】:

  • 只有一件事,您可以在 using 子句中使用 SqlDataReader 以获得更好的方法。 if (reader.HasRows) { while (reader.Read()) { Console.WriteLine("{0}: {1:C}", reader[0], reader[1]); } } else { Console.WriteLine("没有找到行。"); }
  • @ydobonmai 有点超前了……但如果你想挑剔,SqlCommand 也是一次性的。还不如在我们处理时添加异常处理。哎呀,让我们为他编写提问者的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-16
  • 1970-01-01
  • 2023-03-19
  • 2012-07-14
  • 2013-08-07
相关资源
最近更新 更多