0
点赞
收藏
分享

微信扫一扫

C# 读取Access表格数据 或者mdb数据 顺序反了

椰果玩安卓 2022-04-14 阅读 60
c#

C# 读取表格返回数据顺序与表格中数据反了,初步估计是因为前面是空值,从最后一行开始读取了。 

如果按升序读取的话,需要加order by

"SELECT * FROM " + _tablename + " ORDER BY " + colnames[0] + " ASC";

降序:

"SELECT * FROM " + _tablename + " ORDER BY " + colnames[0] + " DESC";

程序举例:

        public static string[,] get_a_whole_table_str2Darr_constr2(string _connectionstr, string _tablename)
        {

            string sql1 = "select * from " + _tablename;

            OleDbConnection OleDbConnection1 = new OleDbConnection();

            OleDbConnection1.ConnectionString = _connectionstr;

            OleDbConnection1.Open();

            OleDbDataAdapter OleDbDataAdapter1 = new OleDbDataAdapter(sql1, OleDbConnection1);

            DataTable Table1 = new DataTable();

            OleDbDataAdapter1.Fill(Table1);

            List<string> colnames = new List<string> { };
            foreach (DataColumn column in Table1.Columns)
            {

                colnames.Add(column.ColumnName);

            }

            OleDbConnection1.Close();

            OleDbDataAdapter1.Dispose();


            //string sql2 = "select * from " + _tablename + " order by" + colnames[0] + "asc";

            string sql2 = "SELECT * FROM " + _tablename + " ORDER BY " + colnames[0] + " ASC";

            OleDbConnection OleDbConnection2 = new OleDbConnection();

            OleDbConnection2.ConnectionString = _connectionstr;

            OleDbConnection2.Open();

            OleDbDataAdapter OleDbDataAdapter2 = new OleDbDataAdapter(sql2, OleDbConnection2);

            DataTable Table2 = new DataTable();

            OleDbDataAdapter2.Fill(Table2);

            int num_rows = Table2.Rows.Count;

            int num_cols = Table2.Columns.Count;

            string[,] str2DResult = new string[num_rows, num_cols];

            for(int i=0; i<num_rows; i++)
            {
                for(int j=0; j<num_cols; j++)
                {
                    str2DResult[i,j] = Table2.Rows[i][j].ToString();
                }
            }

            OleDbConnection2.Close();

            OleDbDataAdapter2.Dispose();

            return str2DResult;
        }

举报

相关推荐

0 条评论