KBD

Keith Devens .com

Saturday, September 6, 2008 Flag waving
Beauty is the first test: there is no permanent place in this world for ugly mathematics. – G. H. Hardy (A Mathematician's Apology)
← ADO.NET for the Java ProgrammerCarrie Underwood's audition video →

Daily link icon Friday, February 10, 2006

Dump a db table in ASP.NET

One of the first things I do whenever I'm working with a new database technology (JDBC, ADO, ADO.NET, etc.) is write a table dumper to learn the API. It's also usually because I usually find myself without access to any handy db tools, so I have to write my own. Here's a dumper for ASP.NET/ADO.NET:

void DumpTable(System.Data.IDataReader reader){
    System.Data.DataTable fields = reader.GetSchemaTable();
    Response.Write("<table border='1'>");
    Response.Write("<tr>");
    foreach(System.Data.DataRow field in fields.Rows){
        Response.Write("<th>");
        Response.Write(HttpUtility.HtmlEncode(field["ColumnName"].ToString()));
        Response.Write("</th>");
    }
    Response.Write("</tr>");
    int numfields = reader.FieldCount;
    while(reader.Read()){
        Response.Write("<tr>");
        for(int i=0; i<numfields; i++){
            Response.Write("<td>");
            string s = reader[i].ToString();
            Response.Write(s.Length == 0 ? "&nbsp;" : HttpUtility.HtmlEncode(s));
            Response.Write("</td>");
        }
        Response.Write("</tr>");
    }
    Response.Write("</table>");
}

There may be a better way to do some of that (if there is, let me know). Just for reference, to connect and get a table dump (happens to be Oracle, but there's an equivalent for every db API in ADO.NET):

OracleConnection conn = new OracleConnection(
   "Data Source=dbtable;User Id=user;Password=pass"
); // wrapped to not break my layout
conn.Open();
OracleCommand cmd = new OracleCommand("SELECT * FROM table WHERE ROWNUM<100", conn);
OracleDataReader reader = cmd.ExecuteReader();

And of course, after dumping:

conn.Close();

That handy WHERE ROWNUM < n bit from here.

Update: For informational purposes, here's a similar utility function for PHP I have sitting around in my db library (modified slightly):

<?php
function printTable(&$table){
    if(!
$table){
        echo 
'Empty table';
        return;
    }
    echo 
'<table border="1">',"\n<tr>\n\t";
    foreach(
array_keys($table[0]) as $key)
        echo 
'<th>',htmlspecialchars($key),'</th>';

    foreach(
$table as $row){
        echo 
"\n</tr>\n<tr>\n\t";
        foreach(
$row as $data)
            echo 
'<td>',htmlspecialchars($data),'</td>';
    }
    echo 
"\n</tr>\n</table>\n\n";
}
?>
← ADO.NET for the Java ProgrammerCarrie Underwood's audition video →

Comments XML gif

Hannibal wrote:

1. This code compiled...ship it!
2. I just finished my third martini.
3. I still think this will probably work (please let me know if it does not).

    // call this like: KeithTakesADump(sqlDataReader, Response.Output);
    public static void KeithTakesADump(IDataReader reader, TextWriter output)
    {
        HtmlTextWriter writer = new HtmlTextWriter(output);
        writer.WriteFullBeginTag("table");
        writer.WriteFullBeginTag("tr");
        for (int i = 0; i < reader.FieldCount; ++i)
        {
            writer.WriteFullBeginTag("td");
            writer.Write(reader.GetName(i));
            writer.WriteEndTag("td");
        }
        writer.WriteEndTag("tr");
        while (reader.Read())
        {
            writer.WriteFullBeginTag("tr");
            for (int i = 0; i < reader.FieldCount; ++i)
            {
                writer.WriteFullBeginTag("td");
                writer.Write(reader[i].ToString());
                writer.WriteEndTag("td");
            }
            writer.WriteEndTag("tr");
        }
    }
∴ Hannibal | 11-Feb-2006 6:43pm est | #9122

Keith (http://keithdevens.com/) wrote:

Ah, reader.GetName(i). Didn't see that one!

But HtmlTextWriter? Icky!

Keith | 11-Feb-2006 9:56pm est | http://keithdevens.com/ | #9124

Hannibal wrote:

HtmlTextWriter is not icky. It is faster to type and the output is formatted.

∴ Hannibal | 12-Feb-2006 5:19am est | #9126

Keith Gaughan (http://talideon.com/) wrote:

I agree with Keith: it is icky. For a start, There's the WriteFullBeginTag() and WriteEndTag() methods: ew! This is duplication of effort. You shouldn't have do this! You should be able to create an element, giving its name and attributes, and insert child elements and text elements into it. And when you request a child element to be added, the method should return an object representing it, which you can then manipulate further. When you're done, simply use ToString() and write the result wherever you want. In fact, if I have some free time tomorrow, I'll prototype it and throw it up online.

That, and HtmlTextWriter is overkill. You're not going looking at the source it generates (so nicely formatted output isn't a necessity), and all you really want is a dump of a table. It works just fine.

∴ Keith Gaughan | 14-Feb-2006 12:44am est | http://talideon.com/ | #9136

Feel free to post a comment below. Please see my comment policy.

Formatting Rules (No HTML):

  • **bold**, *italic*, _underlined_, --strikeout--
  • "text"="url" creates a link, and URLs are auto-highlighted
  • Blockquote: Like e-mail, begin paragraph with > (greater-than sign)
  • Lists: begin paragraph with *,-, or + (unordered), or # (ordered)
  • Code block: ?!code:language=perl|php|sql|javascript|etc.{\n}...{\n}?!/code

:
(will be your IP address if blank)
: (optional)
(Will not be shown on site)

: (optional)
:

September 2008
SunMonTueWedThuFriSat
 123456
78910111213
14151617181920
21222324252627
282930 



RSS feed RSS feed for Keith's Weblog
Atom feed Atom feed for Keith's Weblog
Weblog archive
Recent comments
  on 5 posts

Recent comments XML

new⇒I hate ASP.NET

CF, why pick that piece of trash?​Cold Confusion. Is it finally​really a OO...

ColdConfusion: Sep 5, 8:36pm

new⇒Maps of Iraq

This is for Linda, I will be​visiting that site some time in the​near futur...

Bob: Sep 5, 1:20pm

Girls, please don't get breast implants

Well alright I just read my above​comment and I wanted to add​this...I shou...

76.66.140.8: Sep 4, 7:31pm

Spider solitaire

I don't think the question was​necessarily if there are unbeatable​games.  ...

Jared: Sep 4, 12:44pm

Convert Pantone Colors to RGB and Hex - Color Conversion Chart

The colors on those website don't​seem to relate to the pantone data​we hav...

blah: Sep 3, 10:12am

Generated in about 0.21s.

(Used 8 db queries)

mobile phone