C#数据流返回DataTable

        public static DataTable GetTable(string sqlText, Dictionary dic, IDbConnection dbConn, bool isClose)
        {
            DataTable dt = null;
            using (IDbCommand cmd = dbConn.CreateCommand())
            {
                cmd.CommandText = sqlText;
                if (dic != null)
                {
                    foreach (var item in dic)
                    {
                        var p = cmd.CreateParameter();
                        p.ParameterName = "@" + item.Key;
                        p.Value = item.Value;
                        cmd.Parameters.Add(p);
                    }
                }
                using (IDataReader reader = cmd.ExecuteReader())
                {
                    int intFieldCount = reader.FieldCount;
                    dt = new DataTable();
                    //设置datatable中列
                    for (int intCounter = 0; intCounter < intFieldCount; ++intCounter)
                    {
                        dt.Columns.Add(reader.GetName(intCounter).ToUpper(), reader.GetFieldType(intCounter));
                    }
                    dt.BeginLoadData();
                    object[] objValues = new object[intFieldCount];
                    while (reader.Read())
                    {
                        reader.GetValues(objValues);
                        dt.LoadDataRow(objValues, true);
                    }
                    reader.Close();
                    dt.EndLoadData();
                }
            }
            if (isClose) //true:关闭连接 false 不关闭连接
            {
                dbConn.Close();
            }
            return dt;
        }

你可能感兴趣的:(C#)