C# 使用ADO.NET从SQL Server获取数据

C# 使用ADO.NET从SQL Server获取数据,c#,sql,sql-server,ado.net,C#,Sql,Sql Server,Ado.net,在SQLServer2008中有这样做的教程吗? 你有例子吗 是否可以执行存储过程并在C#或其他语言中获得结果?一个好的起点是类: 更具体地说: 我建议首先理解这些概念。ADO.NET代码与SQL Server 2005/2008的工作方式没有区别。。这一切都取决于System.Data.SQLClient命名空间提供的对象以及它们之间的关联/区别以及这些对象具有的方法。有一件事,您可以在using子句中使用SqlDataReader以获得更好的方式。如果(reader.HasRows){whi

在SQLServer2008中有这样做的教程吗? 你有例子吗


是否可以执行存储过程并在C#或其他语言中获得结果?

一个好的起点是类:

更具体地说:


我建议首先理解这些概念。ADO.NET代码与SQL Server 2005/2008的工作方式没有区别。。这一切都取决于System.Data.SQLClient命名空间提供的对象以及它们之间的关联/区别以及这些对象具有的方法。有一件事,您可以在using子句中使用SqlDataReader以获得更好的方式。如果(reader.HasRows){while(reader.Read()){Console.WriteLine({0}:{1:C}),reader[0],reader[1]);}}其他{Console.WriteLine(“找不到行”);}@ydobonmai在这里有点超前了。。。但是如果你想挑剔,SqlCommand也是一次性的。还不如在进行时添加异常处理。见鬼,让我们为他写下询问者的代码吧。
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();
    }
}
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();
    }
}