[ASP.NET]用SQLCommand做GetDataTable

  • 1025
  • 0

摘要:[ASP.NET]用SQLCommand做GetDataTable

為了方便其他類別引用,建立為靜態function 

static public DataTable GetDataTable(SqlCommand cmd)
        {
            DataTable dt = new DataTable();
            SqlConnection cn = new SqlConnection("data source=My-PC;initial catalog=Northwind;user id=abc;password=abcdefg;Min Pool Size=10;Connection Timeout=180;");
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            cmd.Connection = cn;
            try
            {
                cn.Open();                
                da.Fill(dt);
            }
            catch
            {
                //exception handling
            }
            finally
            {
                if (cn.State != ConnectionState.Closed)
                {
                    cn.Close();
                }
                cmd.Dispose();
            }
                        
            return dt;
        }