Multiple SQL queries asp.net c#

后端 未结 5 1869
忘掉有多难
忘掉有多难 2020-12-31 18:08

I need to run several queries inside one function, will I have to create a new SqlConnection for each? Or having one connection but different SqlCommands works too?

5条回答
  •  傲寒
    傲寒 (楼主)
    2020-12-31 18:36

    Open only one SQLConnection

    Use the keyworkd Using as it will automatically dispose the connection.

    If you open connection for each one , it can have performance problems.

    Example:

    using (SqlConnection con = new SqlConnection(connectionString))
        {
            //
            // Open the SqlConnection.
            //
            con.Open();
            //
            // The following code shows how you can use an SqlCommand based on the SqlConnection.
            //
            using (SqlCommand command = new SqlCommand("SELECT TOP 2 * FROM Dogs1", con))
            using (SqlDataReader reader = command.ExecuteReader())
            {
            while (reader.Read())
            {
                Console.WriteLine("{0} {1} {2}",
                reader.GetInt32(0), reader.GetString(1), reader.GetString(2));
            }
            }
        }
    

    One more example:

    public  DataTable GetData()
            {
                DataTable dt = new DataTable();
                using (SqlConnection con = new SqlConnection("your connection here")
                {
                    con.Open();
                    using (SqlCommand cmd = con.CreateCommand())
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandText = "your stored procedure here";                    
                        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                        {
                            da.Fill(dt);
                        }
                    }
                }
                return dt;
            }
    

提交回复
热议问题