简体   繁体   中英

How to show column headers and data when pulling data from AS400

Let me start by saying I am a DBA and not really a programmer, but I have been tasked with creating a console application that can pull data from our AS400. I created an ODBC connection and my code below is returning just the values in each column. I need to also pull the column headers as well. Right now I am showing the data in console just to make sure it is pulling correctly, but my end goal is to dump down into sql.

   var strSQL = "Select acact,actyp,acord,acsts,acnxt from ITSFILE.ACTIONSF fetch first 100 row only";
        OdbcCommand cmd = new OdbcCommand(strSQL, cn);
        OdbcDataReader myDataReader;
        myDataReader = cmd.ExecuteReader();
        while (myDataReader.Read())
        {
            Console.WriteLine(myDataReader["acact"].ToString() + " " + myDataReader["actyp"].ToString() + " " + myDataReader["acord"].ToString() + " " + myDataReader["acsts"].ToString() + " " + myDataReader["acnxt"].ToString());

            Console.ReadLine();
        }
        myDataReader.Close();
        cn.Close();
        }

I figured it out. To capture the column headers I used to use OdbcDataAdapter instead of OdbcDataReader and created a loop to first get the columns and then secondly get the data. This worked great for me. Please see my code below.

var strSQL = "Select acact,actyp,acord,acsts,acnxt from ITSFILE.ACTIONSF fetch first 
100 row only";
using (OdbcCommand cmd = new OdbcCommand(strSQL))
        {
            using (OdbcDataAdapter sda = new OdbcDataAdapter())
            {
                cmd.Connection = cn;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);

                    string csv = string.Empty;
                    string filepath = @"C:\Test\test.csv";
                    foreach (DataColumn column in dt.Columns)
                    {
                        csv += column.ColumnName + ',';

                    }
                    csv += "\r\n";
                    foreach (DataRow row in dt.Rows)
                    {
                        foreach (DataColumn column in dt.Columns)
                        {
                            csv += row[column.ColumnName].ToString().Replace(",", 
";") + ',';
                        }
                        csv += "\r\n";
                    }
                    File.WriteAllText(filepath, csv.ToString());
                }
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM