SQL/C# - Best method for executing a query

前端 未结 5 550
谎友^
谎友^ 2020-12-02 01:49

I need to execute a sql query from within a c# class. I have thought of 2 options

  1. Starting a process of sqlcmd.
  2. Using a SqlCommand object.
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 02:03

    From MSDN:

    The following example creates a SqlConnection, a SqlCommand, and a SqlDataReader. The example reads through the data, writing it to the console. Finally, the example closes the SqlDataReader and then the SqlConnection as it exits the Using code blocks.

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

提交回复
热议问题