    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Let's Do C# and MySQL - Part 2 - A Beginning</title>
        <link>https://members.accu.org/index.php/journals/852</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">CVu Journal Vol 17, #6 - Dec 2005 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c93/">176</a>
                    (12)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c93-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c93+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Let's Do C# and MySQL - Part 2 - A Beginning</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 December 2005 06:00:00 +00:00 or Fri, 02 December 2005 06:00:00 +00:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e22" id="d0e22"></a>Last
Time...</h2>
</div>
<p>Last time, I didn't even touch on any form of programming, but I
did cover what MySQL is, how to set up a database and set up some
tables which we will make use of over time. It was quite a useful
exercise for me as I was able to consolidate material which for
some reason didn't quite gel when I was originally taught it.</p>
<p>I did not cover inserting data, deleting data or even
interrogation of data held within the database. There was a reason
for this - it gives me a basis for introducing the MySQL API and
how to code it up. But first, a health warning.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e29" id=
"d0e29"></a>ByteFX.Data.MySQL and MySQL.Data</h2>
</div>
<p>Mono ships with the ByteFX library which includes the
definitions required for working with MySQL. It doesn't ship the
version from the MySQL website, but that can certainly be compiled
and is very easy to get running with the current release of mono.
From what I have been told, VisualStudio.NET also ships with ByteFX
so I will be using that instead of the version from the MySQL
website. It shouldn't really make much of a difference as to which
one is used as they are following the same API1. The names of the
methods used to call a particular activity may not be the same
though.</p>
<p>The best way though is that before the programming begins, that
you understand how to use the MySQL interface to insert, delete and
query data. After that, everything will fall into place.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e36" id="d0e36"></a>Inserting Data
via the MySQL Interface</h2>
</div>
<p>This is very simple indeed and follows the following form</p>
<pre class="programlisting">
insert into &lt;tablename&gt;(&lt;table_elements&gt;) values(&lt;values_to_be_inserted&gt;);
</pre>
<p>In the case of the database started from the last issue (and
which is still available from my home website), I did the
following:</p>
<div class="c3"><img src="/var/uploads/journals/resources/pic1.png" align="middle"></div>
<p>As I say, nothing to it.</p>
<p>I have not updated id - this is set as auto_increment. This
means though that it may not be the number you would expect it to
be. It is now down as being 108 (the database I provided has the
last id number as 107). The problem is that I actually am using id
incorrectly (and quite deliberately so). I had planned to create
the database and tables in one go with id also being the element's
number. While this isn't that important in the bigger scheme of
things, it does mean that I have to enter the data in the correct
elemental order with any snafu's requiring to be deleted.</p>
<p>id can set manually in the same way as any element within the
table. It is, after all, nothing special.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e52" id="d0e52"></a>Editing
Data</h2>
</div>
<p>It is possible to edit the id datafield without resorting to
violence as well (which is quite handy as it means that if instead
of a table of periodic elements, you had something like a stock
list, you can dynamically alter the number of items in stock
quickly and simply).</p>
<p>To edit a parameter</p>
<pre class="programlisting">
update `&lt;tablename&gt;`
set `&lt;element_name&gt;` ='&lt;new_value&gt;'
where `&lt;element_name&gt;`=&lt;old_value&gt; limit 1;
</pre>
<p>or for my example</p>
<div class="c3"><img src="/var/uploads/journals/resources/pic2.png" align="middle"></div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e64" id="d0e64"></a>Deleting
Data</h2>
</div>
<p>Deleting data is an operation that everyone will need to do at
some point or other with a database. An entry may be so messed up
that it is not worth issuing a number of update commands to the
server. It is simpler to just delete the row and re-enter the
data.</p>
<p>To remove a row</p>
<pre class="programlisting">
delete from `&lt;table_name&gt;`
where `&lt;primary_key&gt;`=&lt;value&gt; limit 1;
</pre>
<p>And again, from my database:</p>
<div class="c3"><img src="/var/uploads/journals/resources/pic3.png" align="middle"></div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e76" id="d0e76"></a>Deleting a
Table or Database</h2>
</div>
<p>Of course, there may be times when an entire table is so
completely mucked up that the only real way to resolve the problem
is to delete the table, or in extreme cases, the database. This is
performed using the drop command. Once this command is issued,
there is no going back. The table or database is gone. No more.
Made like an old oak table and vanished.</p>
<pre class="programlisting">
drop table `&lt;table_name&gt;`
</pre>
<p>or</p>
<pre class="programlisting">
drop database `&lt;database_name&gt;`
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e87" id="d0e87"></a>Finding Data
from the Table</h2>
</div>
<p>Once data is in the table, you will someday wish to make use of
it. Again, not a difficult task and a task which is very easy to
modify</p>
<pre class="programlisting">
select &lt;table_elements&gt; from &lt;table_name&gt;;
</pre>
<p>Say I wish to see all elements, their atomic weights and the CAS
registry number, all I do is issue</p>
<pre class="programlisting">
select name, atweight, casreg from elementinfo;
</pre>
<p>which will give</p>
<div class="c3"><img src="/var/uploads/journals/resources/pic4.png" align="middle"></div>
<p>While the database is small, that is useful. However, there are
120 elements in the periodic table - that will mean that the data
presented will certainly fill more than the server window. The
search command is flexible and allows the user to specify to print
(say) all base metal elements. This is achieved by using where
within the select command sequence.</p>
<pre class="programlisting">
select &lt;element_names&gt; from &lt;table_name&gt; where (...);
</pre>
<p>For me to select just the base metal elements, I would use</p>
<pre class="programlisting">
select name, atweight, casreg from elementinfo where (classification = &quot;Base Metal&quot;);
</pre>
<div class="c3"><img src="/var/uploads/journals/resources/pic5.png" align="middle"></div>
<p>The where modified can be used in the same was as an if
conditional can in programming. You can include or and and and even
sort the output!</p>
<pre class="programlisting">
select name, atweight, casreg from elementinfo where (classification=&quot;Base Metal&quot; and atnumber &lt; 12); (See figure 1)
</pre>
<div class="figure"><a name="d0e114" id="d0e114"></a>
<div class="mediaobject c3"><img src="/var/uploads/journals/resources/pic1.png" align=
"middle"></div>
<p class="title c4">Figure 1. </p>
</div>
<pre class="programlisting">
select name, atweight, casreg from elementinfo where (classification=&quot;Base Metal&quot; or block=&quot;f&quot;); (See figure 2)
</pre>
<div class="figure"><a name="d0e121" id="d0e121"></a>
<div class="mediaobject c3"><img src="/var/uploads/journals/resources/pic2.png" align=
"middle"></div>
<p class="title c4">Figure 2. </p>
</div>
<pre class="programlisting">
select name, atweight, casreg from elementinfo where ((classification=&quot;Base Metal&quot; and atnumber &lt; 10) or block=&quot;f&quot;) order by &quot;id&quot;;  (See figure 3)
</pre>
<div class="figure"><a name="d0e128" id="d0e128"></a>
<div class="mediaobject c3"><img src="/var/uploads/journals/resources/pic3.png" align=
"middle"></div>
<p class="title c4">Figure 3. </p>
</div>
<p>Powerful stuff!</p>
<p>As you can also see from the times, retrieval is almost instant.
From tests I've performed, even with absolutely huge databases (in
excess of 2/3rd of a million rows in a single table with the
database containing another 6 tables, each with around &frac14;
million rows), retrieval from the database still gives very small
times - even with a large conditional in the where conditional.</p>
<p>We've now covered the essentials that we will later use for our
database. We have gone through the data types, how to create,
modify and delete as well as interrogate our database and tables.
Let's get on with some coding!</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e139" id="d0e139"></a>Using C# with
MySQL</h2>
</div>
<p>While it would be simple for me to hack out the source using C
and MySQL, I have deliberately chosen C# for two reasons</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>With mono and its implementation of <tt class=
"classname">System.Windows.Forms</tt>, I am able to create a single
executable which will work on any machine with either the mono
runtime or .NET 1.1 installed. This covers the majority of
computers running. The final binary does not need recompiling to
run on another platform.</p>
</li>
<li>
<p>I like C#</p>
</li>
</ol>
</div>
<p>Alright, the second isn't a reason as such, but hey, who is
writing this?</p>
<p>What I'll cover for the rest of this article is connecting to
the server, reading data, inserting data and editing data. It will
not be that hard.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e158" id="d0e158"></a>The Basic
Method</h2>
</div>
<p>As these are stand-alone examples, they will all follow the same
method.</p>
<p>There is actually nothing difficult about any of what we are
about to do, essentially, we will be using a small number of
methods to perform the tasks we need. What makes this even simpler,
is all that we need to do is define a string which contains what we
want to do and then pass that to the C# controller. Who could ask
for anything more?</p>
<p>As you can see in the flowchart (figure 4) I will test to see if
an error has occurred at the connection stage. I'll also be testing
after any connection or process is passed to the database. It is
essential to do this as the application will complain violently if
you attempt to insert, delete or interrogate a table when the query
to the database fails.</p>
<div class="figure"><a name="d0e167" id="d0e167"></a>
<div class="mediaobject c3"><img src="/var/uploads/journals/resources/drawing2.png"
align="middle"></div>
<p class="title c4">Figure 4. </p>
</div>
<p>There are two ways to catch the error. The simplest is that if
the query fails, a non-zero is returned, so using if (!query) ...
should suffice. The second method is to use try / catch (much in
the same way as you would for C++). Below is the simplest method to
connect to the MySQL server</p>
<pre class="programlisting">
using System;
using System.Data;
using ByteFX.Data.MySqlClient;
public class Test
{
  public static void Main(string [] args)
  {
    string connectionString = &quot;Server=localhost;&quot;+
       &quot;Database=theelements&quot;;+
       &quot;User ID=paul;&quot;+
       &quot;Password=paulpassword;&quot;;
    IDbConnection dbcon;
    dbcon = new MySqlConnection(connectionString);
    dbcon.Open();
    if (!dbcon)
    {
      Console.WriteLine(&quot;Unable to connect to the
                        MySQL server&quot;);
      exit(1);
    }
    else
      Console.WriteLine(&quot;Connection made&quot;);
    dbcon.Close();
   dbcon = null;
  }
}
</pre>
<p><tt class="literal">IDbConnection dbcon;</tt> creates an
instance of the C# database connection class. At this point, this
can be a connection to any number of different database types.
<tt class="literal">dbcon.Open()</tt> opens the connection to the
database which by virtue of the line before it, is given as a MySQL
connection.</p>
<p>This can be compiled by issuing (<tt class=
"literal">&lt;compiler&gt;</tt> can be either <span class=
"application">csc</span> or <span class="application">mcs</span>
here) <tt class="literal">&lt;compiler&gt; mysql.cs -r:System.Data
-r:ByteFX.Data</tt> which will create an executable called
<tt class="filename">mysql.exe</tt>.</p>
<p>Test the binary. Assuming everything went well, you will have
seen the line <tt class="literal">Connection made</tt> before the
application terminated. If it didn't work, you will need to ensure
that your listing matches mine and that the MySQL server is running
(it's caught me out a couple of times before now).</p>
<p>We can now connect to any MySQL database! Let's do something a
bit more taxing - reading data from the database (which is defined
in the <tt class="literal">commandString</tt> line).</p>
<p>This creates another instance of <tt class=
"classname">IDbCommand</tt>, this time it is an instance of
<tt class="literal">dbcon.CreateCommand()</tt>. The command to be
used is created and <tt class="literal">dbcmd.CommandText</tt> is
set to equal the command. The command is then acted upon.
<tt class="methodname">CommandText</tt> is able to either get or
set from the database by the type passed to it. If it is a
<tt class="type">string</tt> (as it is here), the command is a
<tt class="literal">get</tt> (the information is retrieved). If it
is passed a <tt class="type">void</tt>, the command is <tt class=
"literal">set</tt>. Again, test using <tt class="literal">if
(!(dbcmd.CommandText = sqlcommand)) ...</tt></p>
<p>I need to explain <tt class="classname">IDbCommand</tt> here as
this interface represents a database command. To execute a command
against a database, there has to be an open connection and a
properly configured command object for the database type. These
&quot;command objects&quot; can be created using a constructor, but it is far
simpler to use the <tt class="methodname">CreateCommand</tt>
method. This returns a command object of the correct type for the
database type and even goes as far as to configure the command
object with the basic information obtained in the connection. The
command object should have the properties in table 1 set; these are
common to all command implementations</p>
<div class="table"><a name="d0e246" id="d0e246"></a>
<table summary="Common command object properties" border="1"
cellspacing="0">
&lt;colgroup&gt;
&lt;col width=&quot;50%&quot;&gt;
&lt;col width=&quot;50%&quot;&gt;&lt;/colgroup&gt;
&lt;thead&gt;
<tr>
<th>Property</th>
<th>Description</th>
</tr>
&lt;/thead&gt;
&lt;tbody&gt;
<tr>
<td>CommandText</td>
<td>A string containing the text of the SQL command to execute OR
the name of a stored procedure (I'll cover these at a later time).
This must be compatible with the value specified in the CommandType
property</td>
</tr>
<tr>
<td>CommandTimeout</td>
<td>An int which sets a time (in seconds) to wait for the command
to return before timing out and raising an exception. The default
is 30 seconds and the parameter is commonly omitted.</td>
</tr>
<tr>
<td>CommandType</td>
<td>A value of the <tt class="type">System.Data.CommandType</tt>
enumeration that specifies the type of command represented by the
command object. For most data providers, there are 3 valid values:
1. StoredProcedure. For use when you wish to execute a stored
procedure 2. Text. This is for executing a SQL text command 3.
TableDirect. This will return the entire contents of one or more
tables. The default is Text.</td>
</tr>
<tr>
<td>Connection</td>
<td>An IDbConnection instance that provides the connection to the
database which you want to act upon. If the command is created
using the <tt class="methodname">IDbConnection.CreateCommand</tt>
method, the property with be automatically be set to the
IDbConnection instance from which the command was created.</td>
</tr>
<tr>
<td>Parameters</td>
<td>A <tt class=
"classname">System.Data.IDataParameterCollection</tt> instance
containing the set of parameters to substitute into the
command.</td>
</tr>
<tr>
<td>Transaction</td>
<td>A <tt class="classname">System.Data.IDbTransaction</tt>
instance representing the transaction into which to enlist the
command.</td>
</tr>
&lt;/tbody&gt;
</table>
<p class="title c4">Table 1. Common command object properties</p>
</div>
<p>You will meet these later in the article.</p>
<p>Next is to read the data. This is performed using <tt class=
"classname">IDataReader</tt>. This provides a means of reading one
or more forward-only streams of result sets obtained by executing a
command at a data source and has quite a number of classes. The
important aspect to this though is that it is a sequential reader
(in other words, it grabs one line at a time until the end of the
read process).</p>
<pre class="programlisting">
sqlcommand = &quot;select elementname, atweight, casreg from elementinfo&quot;;
dbcmd.CommandText = sqlcommand;
IDataReader reader = dbcmd.ExecuteReader();
while (reader.Read())
{
  string element = (string) reader[&quot;elementname&quot;];
  float atweight = (float) reader[&quot;atweight&quot;];
  long cas = (long) reader[&quot;casreg&quot;];
  Console.WriteLine(&quot;Element - &quot; + element + &quot;,
     weight &quot;+ atweight + &quot;, CAS : &quot;+ cas;
}
</pre>
<div class="sidebar">
<p class="title c4">Handy Hint for Linux Users</p>
<p>Normally, you will need to test the application using <tt class=
"literal">mono&lt;appname&gt;.exe</tt>. A simpler way to get around
this is to edit your <tt class="filename">.bashrc</tt> to include
the line:</p>
<pre class="programlisting">
echo `:CLR:M::MZ::/usr/bin/mono:' &gt;
/proc/sys/fs/binfmt_misc/register
</pre>
<p>This will only work if your kernel has the use misc. binary
formats installed - you will know this if you have a directory
called <tt class="filename">/proc/sys/fs/binfmt_misc</tt>.</p>
</div>
<p>Again, a command is passed to <tt class=
"methodname">CommandText</tt>. However, this time the command needs
something to do the reading for it. The <tt class=
"classname">IDataReader</tt> class performs such a task and it is
easy to see what is happening with the interesting part being two
fold. The first is the <tt class="classname">IDataReader</tt> is
positioned before the first element of the database by default, so
a <tt class="methodname">Read()</tt> has to be performed before
anything useful comes out. The second is that as the database could
contain any number of field types, the <tt class=
"methodname">Read()</tt> returns everything as <tt class=
"type">void*</tt> which then needs to be recast to the correct type
for the data.</p>
<p>To terminate the application, <tt class="varname">reader</tt>
and <tt class="varname">dbcon</tt> have to be closed and before
<tt class="varname">dbcon</tt> is closed, <tt class=
"varname">dbcmd</tt> has to be disposed of.</p>
<pre class="programlisting">
Reader.Close();
reader = null;
dbcmd.Dispose();
dbcmd = null;
dbcon.Close();
dbcon = null;
</pre>
<p>The full listing is now</p>
<pre class="programlisting">
using System;
using System.Data;
using ByteFX.Data.MySqlClient;
public class Test
{
  public static void Main(string [] args)
  {
    string connectionString = &quot;Server=localhost;&quot;+
       &quot;Database=theelements;&quot;+ &quot;User ID=paul;&quot;+
       &quot;Password=thelinuxman;&quot;;
    IDbConnection dbcon;
    dbcon = new MySqlConnection(connectionString);
    dbcon.Open();
    IDbCommand dbcmd = dbcon.CreateCommand();
    string sql = &quot;SELECT name, atweight, casreg &quot;+
                 &quot;FROM elementinfo&quot;;
    dbcmd.CommandText = sql;
    IDataReader reader = dbcmd.ExecuteReader();
    while(reader.Read())
    {
      string element = (string) reader[&quot;name&quot;];
      float atweight = (float) reader[&quot;atweight&quot;];
      long cas = (long) reader[&quot;casreg&quot;];
      Console.WriteLine(&quot;Element - &quot;+ element + &quot;,
         weight &quot;+ atweight +&quot;, CAS : &quot;+ cas);
    }
    reader.Close();
    reader = null;
    dbcmd.Dispose();
    dbcmd = null;
    dbcon.Close();
    dbcon = null;
  }
}
</pre>
<p>If this application is now compiled and executed, the following
output is seen.</p>
<div class="c3"><img src="/var/uploads/journals/resources/csharp.png" align=
"middle"></div>
<p>That's reading out of the way - by altering the <tt class=
"literal">sqlcommand</tt> line, you can include <tt class=
"literal">where</tt> and <tt class="literal">order by</tt>
parameters. Writing and editing is not a great deal more difficult.
However, <tt class="classname">IDataReader</tt> does warrant a
deeper look.</p>
<p>The <tt class="classname">IDataReader</tt> extends the
<tt class="classname">System.Data.IDataRecorder</tt> interface and
together, these declare the functionality that gives the access to
all aspects of the data contained in the result. Table 2 describes
some of the more commonly used members of the interfaces.</p>
<div class="table"><a name="d0e391" id="d0e391"></a>
<table summary="Commonly used members of the DataReader classes"
border="1" cellspacing="0">
&lt;colgroup&gt;
&lt;col width=&quot;50%&quot;&gt;
&lt;col width=&quot;50%&quot;&gt;&lt;/colgroup&gt;
&lt;thead&gt;
<tr>
<th>Member</th>
<th>Comments</th>
</tr>
&lt;/thead&gt;
&lt;tbody&gt;
<tr>
<td><span class="bold"><b>Property</b></span></td>
<td> </td>
</tr>
<tr>
<td>FieldCount</td>
<td>Gets the number of columns in the current row</td>
</tr>
<tr>
<td>IsClosed</td>
<td>Returns true if IDataReader is closed, else false</td>
</tr>
<tr>
<td>Item</td>
<td>Returns an object representing the value of the specified
column in the current row. The column can be specified either by
the name or zero-based integer index. This is the indexer for data
reader classes.</td>
</tr>
<tr>
<td><span class="bold"><b>Method</b></span></td>
<td> </td>
</tr>
<tr>
<td>GetDataTypeName</td>
<td>Gets the name of the data source data type for a given
column</td>
</tr>
<tr>
<td>GetFieldType</td>
<td>Gets a System.Type instance representing the data type of the
value contained in the column specified (uses a zero-based integer
index)</td>
</tr>
<tr>
<td>GetName</td>
<td>Gets the name of a column specified (uses a zero-based integer
index)</td>
</tr>
<tr>
<td>GetOrdinal</td>
<td>Gets the zero-based column ordinal for the column with the
specified name</td>
</tr>
<tr>
<td>GetSchemaTable</td>
<td>Returns a System.Data.DataTable instance that contains metadata
describing the columns contained in IDataReader.</td>
</tr>
<tr>
<td>IsDBNull</td>
<td>Returns true if the value in a specified column contains a NULL
value, else false.</td>
</tr>
<tr>
<td>NextResult</td>
<td>If IDataReader includes multiple result sets (due to multiple
statements being executed), NextResult moves to the next set of
results.</td>
</tr>
<tr>
<td>Read</td>
<td>Advances the reader to the next record.</td>
</tr>
&lt;/tbody&gt;
</table>
<p class="title c4">Table 2. Commonly used members of the
DataReader classes</p>
</div>
<p>In addition to that little lot, the data reader also provides a
pile of other methods which takes an integer argument (the
zero-based index of the column) - the names are self-explanatory :
<tt class="methodname">GetBoolean</tt>, <tt class=
"methodname">GetByte</tt>, <tt class="methodname">GetBytes</tt>,
<tt class="methodname">GetChar</tt>, <tt class=
"methodname">GetChars</tt>, <tt class=
"methodname">GetDateTime</tt>, <tt class=
"methodname">GetDecimal</tt>, <tt class=
"methodname">GetDouble</tt>, <tt class="methodname">GetFloat</tt>,
<tt class="methodname">GetGuid</tt>, <tt class=
"methodname">GetInt16</tt>, <tt class="methodname">GetInt32</tt>,
<tt class="methodname">GetInt64</tt>, <tt class=
"methodname">GetString</tt>, <tt class="methodname">GetValue</tt>
and <tt class="methodname">GetValues</tt>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e517" id="d0e517"></a>Writing and
Editing in C#</h2>
</div>
<p>This is, again, quite simple. We have seen that with reading,
<tt class="methodname">CreateCommand</tt> was called. Virtually the
same procedure is used for writing and updating.</p>
<p>Inserting fresh data is virtually the same as if you were using
the MySQL monitor</p>
<pre class="programlisting">
IDbCommand dbcmd = dbcon.CreateCommand();
string mysqlcommand = &quot;insert into 
   elementinfo(id, name, ...) &quot;;
mysqlcommand += &quot;values(23, @name, ...)&quot;;
dbcmd.Parameters.Add(&quot;@name&quot;, &quot;Sodium&quot;);
dbcmd.CommandText = mysqlcommand;
</pre>
<p>You can see a slight addition here, the use of <tt class=
"methodname">Parameters.Add(...)</tt>. The reason for using this is
that as you know, when adding data, you can be adding absolutely
anything in. If you want to pass in a string literal though, you
would normally need these to be passed in quotes. Effectively, that
is what is happening here. By using <tt class=
"methodname">Parameters.Add()</tt>, we can pass anything in without
the requirement to use quotes.</p>
<pre class="programlisting">
IDbCommand dbcmd = dbcon.CreateCommand();
string mysqlcommand = &quot;update elementinfo
set id = 23 where id = 108&quot;
dbcmd.CommandText = mysqlcommand;
if (dbcmd.ExecuteNonQuery() == 1)
  Console.WriteLine(&quot;ID updated&quot;);
else
  Console.WriteLine(&quot;ID not updated&quot;);
</pre>
<p>For any operation which doesn't return database data (such as
table creation, table deletion or inserting), <tt class=
"methodname">ExecuteNonQuery()</tt> should be used. This method
returns an <tt class="type">int</tt> that specified the number of
rows affected (create table returns -1). Both of these code
snippets can be placed into code listing already given</p>
<p>That's enough for this time. Next time, I'll expand on this via
a simple menu system for interrogation, insertion and deletion of
data and move that simple menu system to use <tt class=
"classname">System.Windows.Forms</tt></p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
