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

标签 c# sql sql-server ado.net

是否有任何教程可以在 SQL Server 2008 中执行此操作? 你有例子吗?

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

最佳答案

开始的好地方是 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();
    }
}

关于c# - 使用 ADO.NET 从 SQL Server 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5306684/

相关文章:

c# - 如何在 C# 中订购字典?

c# - 没有递归或无限循环的 StackOverflowException?

mysql - 我不能将外键分配给不是另一个表的主表的表吗?

java - 用java中的sql查询更新5个组合框

sql - 如何知道未提交的事务是否试图将特定的唯一键插入 SQL

c# - Entity Framework 4.3.1 无法创建(/打开)数据库 [线程异常?]

c# - EF核心: The instance of entity type cannot be tracked and context dependency injection

sql-server - SparkSQL MS SQL Server,编译后获取消息 "No suitable driver"

sql - 在 SQL Server 中查找最近的日期

c# - WPF ObservableList 调度程序线程