SqlCommand or SqlDataAdapter?

后端 未结 6 1037
鱼传尺愫
鱼传尺愫 2020-12-10 05:21

I\'m creating something like a small cashier application that keeps record for the clients, employees, services, sales, and appointments. I\'m using windows forms, and withi

6条回答
  •  青春惊慌失措
    2020-12-10 05:40

    If you are just reading data and not doing updates/inserts/deletes, then SqlDataReader will be faster. You can also combine it with a DataSet. If you wrap the data access objects with using statements, the runtime will handle the connection cleanup logic for you.

    A pattern I often use for synchronous access is something like this:

    DataTable result = new DataTable();
    using (SqlConnection conn = new SqlConnection(MyConnectionString))
    {
        using (SqlCommand cmd = new SqlCommand(MyQueryText, conn))
        {
            // set CommandType, parameters and SqlDependency here if needed
            conn.Open();
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                result.Load(reader);
            }
        }
    }
    

    For updates/deletes/inserts, a SqlDataAdapter might be worth considering, but usually only if you already have your data in a DataSet. Otherwise, there are faster/better ways of doing things.

提交回复
热议问题