|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionAccessing databases is a common part of most applications and with the introduction of C# and ADO.NET, has become quite simple. This article will demonstrate the four most basic database operations.
These operations will be performed against a Microsoft Access 2000 database, however SQL or other ADO data sources could be used by simply changing the connection string. Getting startedTo use the ADO classes we need to include the ADO.NET namespace and a few handy date classes. Add the following line of code to the file where you want to perform the database operation. It should appear below the namespace line and above the class definition. using System.Data; // State variables using System.Data.ADO; // Database using System.Globalization; // Date Depending on the type of project you are working with, you may need to add a
reference to the
The connection string is used during most operations, so I would recommend you make it a member of the class you will be working in. Note: In your application the path to the database file would be something else. //Attributes public const string DB_CONN_STRING = "Driver={Microsoft Access Driver (*.mdb)}; "+ "DBQ=D:\\CS\\TestDbReadWrite\\SimpleTest.mdb"; Reading dataNow things get interesting. Reading is done using the
However, as good programmers we would have also wrapped the lot in a try/catch/finally to ensure we handled anything bad. try { .... the database operations ... } catch( Exception ex ) { System.Console.WriteLine( "READING:" ); System.Console.WriteLine( " ERROR:" + ex.Message ); System.Console.WriteLine( " SQL :" + sSqlCmd ); System.Console.WriteLine( " Conn.:" + DB_CONN_STRING ); } finally { // Close the connection if( conn.State == DBObjectState.Open ) conn.Close(); } Reading different data typesThe int nOrdinalAge = dr.GetOrdinal( "Age" ); int nAge = dr.GetInt32( nOrdinalAge ); DateTime tUpdated = (DateTime)dr["Updated"]; Note the use of int nOrdinalAge = dr.GetOrdinal( "Age" ); if( dr.IsNull( nOrdinalAge ) ) { System.Console.WriteLine( " Age : Not given!" ); } else { int nAge = dr.GetInt32( nOrdinalAge ); System.Console.WriteLine( " Age : " + nAge ); } Insert, Modify, Delete and other SQL commandsInserting, Modifying and Deleting can very simply be done using SQL statements. The following code performs a SQL command to insert a record. // SQL command String sSQLCommand = "INSERT INTO Person (Age, FirstName, Description, Updated) " + "VALUES( 55, 'Bob', 'Is a Penguin', '2001/12/25 20:30:15' );"; // Create the command object ADOCommand cmdAdder = new ADOCommand( sSQLCommand, DB_CONN_STRING); cmdAdder.ActiveConnection.Open(); // Execute the SQL command int nNoAdded = cmdAdder.ExecuteNonQuery(); System.Console.WriteLine( "\nRow(s) Added = " + nNoAdded + "\n" ); Note: The try/catch was not shown in the above example but should wrap the above code. InsertingThe above code inserted a record by building a SQL command which was later executed. Some things to note in the formatting of the command are;
ModifyingThe UPDATE command indicates the records to be modified and the modification to be made. The return value of the ExecuteNonQuery() indicates the number of records changes so this would return 5 if there were 5 Peter's in the table. String sSQLCommand = "UPDATE Person SET Age = 27 WHERE FirstName = 'Peter'"; DeletingThe DELETE command indicates the records to be deleted. This could be several
several records. The return value of the String sSQLCommand = "DELETE FROM Person WHERE FirstName = 'Bobo'"; About the sample codeThe sample is a simple console application that perform each of the database
operations on a provided Microsoft Access database. To build it, open the
TestDbReadWrite.csproj file as a project in the Visual Studio.NET IDE. Change
the ConclusionNow you should be able to perform the basic database operation in C#, get out there and cut some code. Take the time to learn SQL. Also read articles on the why and how this works. If you get really bored check out my site at www.mctainsh.com for more updates on simple coding.
|
||||||||||||||||||||||