CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET...

28
CSci485 C# Lecture 1 - Antonios Das CSci485 C# Lecture 1 - Antonios Das kos kos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos Antonios Daskos

Transcript of CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET...

Page 1: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

An Introduction to C# and Database Programming with

ADO.NET

Antonios DaskosAntonios Daskos

Page 2: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

OutlineOutline

Object Oriented Programming (OOP) Object Oriented Programming (OOP) .NET Introduction.NET IntroductionC# basicsC# basicsVS.NETVS.NETDatabases with C# (ADO.NET)Databases with C# (ADO.NET)

Page 3: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

.NET Framework.NET Framework

Development languagesDevelopment languages C++, C#, VB, J#, JScript, Python, Perl, Fortran, S#, C++, C#, VB, J#, JScript, Python, Perl, Fortran, S#,

Cobol, ASP, XSLT, Eiffel… More than 20 languagesCobol, ASP, XSLT, Eiffel… More than 20 languages Integrated Development Environments (IDEs)Integrated Development Environments (IDEs)

Visual Studio.NET, Mono ProjectVisual Studio.NET, Mono Project Common Language Infrastructure (CLI) and Common Language Infrastructure (CLI) and

Common Language Runtime (CLR)Common Language Runtime (CLR) A specification and its implementationA specification and its implementation Provides a common managed runtime for all Provides a common managed runtime for all

supported languagessupported languages Common Type System (CTS)Common Type System (CTS)

Page 4: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

.NET Framework .NET Framework (cont.)(cont.)

IL (Intermediate Language) and Just In Time (JIT) CompilationIL (Intermediate Language) and Just In Time (JIT) Compilation Language independenceLanguage independence Abstraction similar to Java’s Virtual Machine only more genericAbstraction similar to Java’s Virtual Machine only more generic PortabilityPortability

Framework Base Class LibraryFramework Base Class Library NamespacesNamespaces Memory Management and Garbage CollectionMemory Management and Garbage Collection Plethora of documentation, examples or tipsPlethora of documentation, examples or tips

MSDN: provided to you; also available online atMSDN: provided to you; also available online athttp://http://msdn.microsoft.com/library/default.aspmsdn.microsoft.com/library/default.asp

Programming web sites and forums Programming web sites and forums (most of the times your question has (most of the times your question has been answered before – needs patience and good search keywords)been answered before – needs patience and good search keywords)

Search enginesSearch engines Books, magazines, newsgroups…Books, magazines, newsgroups…

Page 5: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

OOP: a software construction OOP: a software construction paradigmparadigm

Objects Objects Abstract concepts, basic entities that describe internal information Abstract concepts, basic entities that describe internal information

((variablesvariables) and the means to access it, change its state, perform actions ) and the means to access it, change its state, perform actions ((functionsfunctions))

In C# (like Java and most OOP languages) In C# (like Java and most OOP languages) everythingeverything is an object is an object ClassesClasses

Programmer-defined types that model the parts of the system (objects)Programmer-defined types that model the parts of the system (objects) a blueprint for instancesa blueprint for instances

InstancesInstances Building blocks of the codeBuilding blocks of the code Allocated in memory sharing the code but not the dataAllocated in memory sharing the code but not the data

Methods / FieldsMethods / Fields Primary mechanisms (code common to all instances of a class) and Primary mechanisms (code common to all instances of a class) and

data variablesdata variables Static parts: belong to a class, accessible and shared by all instancesStatic parts: belong to a class, accessible and shared by all instances ScopeScope

Page 6: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

OOP: a software construction OOP: a software construction paradigm paradigm (cont.)(cont.)

AbstractionAbstraction InheritanceInheritance PolymorphismPolymorphism EncapsulationEncapsulation Simple example (don’t worry about all the new things):Simple example (don’t worry about all the new things):

……public class MyNumber {public class MyNumber {

int val = 20;int val = 20;

public int value() {public int value() {return val;return val;

}}public int increase(int how_much) {public int increase(int how_much) {

val += how_much; //val = val + how much;val += how_much; //val = val + how much;return val;return val;

}}}}……MyNumber m = new MyNumber();MyNumber m = new MyNumber();int l = m.value(); // l will be 20int l = m.value(); // l will be 20int k = m.increase(12); // k will be 32int k = m.increase(12); // k will be 32

Page 7: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

C# C# BasicsBasics Case sensitiveCase sensitive Common data types (primitives):Common data types (primitives):

bool, byte, short/int/long, float/double, char/stringbool, byte, short/int/long, float/double, char/string ConversionConversion

implicitlyimplicitly float f = 56;float f = 56;

by by castingcasting int i = (int)5.6;int i = (int)5.6;

with convert classwith convert class int i = System.Convert.ToInt32(3.25d);int i = System.Convert.ToInt32(3.25d);

provided methodsprovided methods string s = (5.25).ToString(); //a bit uncommon but it worksstring s = (5.25).ToString(); //a bit uncommon but it works

Page 8: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

C# C# Basics IIBasics II Operators:Operators:

+,-,*,/,%+,-,*,/,% &,|,…, &&, ||, …&,|,…, &&, ||, … ++,--…++,--… <, >, ==,…<, >, ==,… ??

Decision making: Decision making: if...then…elseif...then…else do…while, while, for do…while, while, for ForeachForeach

e.g foreach (int i in list_of_ints) { … }e.g foreach (int i in list_of_ints) { … } switch (more strict than c++/java)switch (more strict than c++/java)

Declarations and scopeDeclarations and scope Comments like c++ Comments like c++ (try Ctrl-K-C and Ctrl-K-U for mass commenting ;-)(try Ctrl-K-C and Ctrl-K-U for mass commenting ;-)

Page 9: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

C# ClassesC# Classes Everything is a class derived from class ObjectEverything is a class derived from class Object Namespaces to avoid confusionNamespaces to avoid confusion Create new instances with keyword Create new instances with keyword newnew

string s1 = new string(‘T’,3); //s1 = “TTT”string s1 = new string(‘T’,3); //s1 = “TTT” Reference their methods with dot (.)Reference their methods with dot (.)

string s2 = s2.ToLowerstring s2 = s2.ToLower (); //s2 = “ttt”(); //s2 = “ttt” Parameters inside brackets as in the constructorParameters inside brackets as in the constructor Public/private, static, finalPublic/private, static, final Try looking at existing examples all around if Try looking at existing examples all around if

unfamiliar with syntax; may find it easier to edit unfamiliar with syntax; may find it easier to edit existing code at firstexisting code at first

Page 10: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

C#: Hello world!C#: Hello world! using System;using System;

class MyAppclass MyApp{{

static void Main ()static void Main (){{

Console.WriteLine ("Hello worldConsole.WriteLine ("Hello world!!");");}}

}} To execute this you need:To execute this you need:

Install .NET Framework (you already have if you installed VS.NET)Install .NET Framework (you already have if you installed VS.NET) Write the code as text in a file, e.g. MyApp.csWrite the code as text in a file, e.g. MyApp.cs Compile it with C# compiler (csc.exe)Compile it with C# compiler (csc.exe)

C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\csc.exe in my machineC:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\csc.exe in my machine Add it to path for convenienceAdd it to path for convenience

Run the produced executable e.g. MyApp.exeRun the produced executable e.g. MyApp.exe

Page 11: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

C#: Useful librariesC#: Useful libraries System.Math classSystem.Math class

e.g. e.g. double d = Math.Pow(5,3); //d = 5double d = Math.Pow(5,3); //d = 533

System.Collections class e.g.ArrayList, Hashtable, System.Collections class e.g.ArrayList, Hashtable, Stack, SortedList, etc. Stack, SortedList, etc. ArrayList a = new ArraList();ArrayList a = new ArraList();a.Add(5); a.Add(6.7);a.Add(5); a.Add(6.7);int i = (int)a[0];int i = (int)a[0];double d = (double)a[1];double d = (double)a[1];

Regular expressions (System.Text.RegularExpressions)Regular expressions (System.Text.RegularExpressions) File Input/Output (System.IO)File Input/Output (System.IO) Networking (System.Net and System.Net.Sockets)Networking (System.Net and System.Net.Sockets) ThreadingThreading

Page 12: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

C#: ConsoleC#: Console Two very common functions for console applications:Two very common functions for console applications:

Write(…): Writes the specified information to the standard Write(…): Writes the specified information to the standard output streamoutput stream

WriteLine(…): Like Write() only followed by the current line WriteLine(…): Like Write() only followed by the current line terminatorterminator

Read(…): Reads the next character from the standard input Read(…): Reads the next character from the standard input streamstream

ReadLine(…): Reads the next line of characters from the ReadLine(…): Reads the next line of characters from the standard input streamstandard input stream

To prevent the execution of a program from terminating To prevent the execution of a program from terminating when done you can add all the code in a try-block with a when done you can add all the code in a try-block with a Console.ReadLine() in the finally-block (see next slide for Console.ReadLine() in the finally-block (see next slide for exception handling)exception handling)

Page 13: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

C#: ExceptionsC#: Exceptions try {try {

…… //code that can generate errors //code that can generate errors //and throw exceptions//and throw exceptions

} catch (ExceptionType1 ex1) {} catch (ExceptionType1 ex1) {… … //code to handle type1 exceptions//code to handle type1 exceptions

} catch (ExceptionType2 ex2) {} catch (ExceptionType2 ex2) {… … //code to handle type1 exceptions//code to handle type1 exceptions

} catch {} catch {…… //code to handle the rest of the //code to handle the rest of the

exceptionsexceptions} finally {} finally {

…… //code to be executed regardless//code to be executed regardless}}

Page 14: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

Visual Studio.NETVisual Studio.NET

Allows for all sorts of projects (Windows apps, Allows for all sorts of projects (Windows apps, ASP projects, Web Services, etc)ASP projects, Web Services, etc)

New C# project:New C# project: File File New New Project Project Choose “Visual C# Projects” andChoose “Visual C# Projects” and

Console Application for simple console programsConsole Application for simple console programs Windows Application for a project with GUIWindows Application for a project with GUI

Choose project’s name and pathChoose project’s name and path

Possibly the project will contain VS.NET Possibly the project will contain VS.NET generated codegenerated code

Page 15: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

Visual Studio.NET Visual Studio.NET (cont.)(cont.)

Colors help reading your code and indicate simple errors Colors help reading your code and indicate simple errors real timereal time

Compiling or running the code will indicate all compile Compiling or running the code will indicate all compile time errors. Runtime errors might still occurtime errors. Runtime errors might still occur

Debugger, code tracing, breakpoints and watches are Debugger, code tracing, breakpoints and watches are invaluable tools – learn the shortcuts and how to use invaluable tools – learn the shortcuts and how to use themthem

IntellisenseIntellisense Makes typing fasterMakes typing faster No need to remember exact function namesNo need to remember exact function names Demonstrates parameters and short descriptionsDemonstrates parameters and short descriptions Reveals an object’s methods – you can do miracles by just a Reveals an object’s methods – you can do miracles by just a

little guessinglittle guessing

Page 16: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

ADO.NETADO.NET

Two sets of classes:Two sets of classes: Managed Provider ClassesManaged Provider Classes

Connecting to the databaseConnecting to the database Data manipulation through SQLData manipulation through SQL Forward-only reading of dataForward-only reading of data

Generic Data ClassesGeneric Data Classes Offline data managingOffline data managing Non-sequential access and editing of data by C# codeNon-sequential access and editing of data by C# code

Page 17: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

ADO.NET:ADO.NET:Managed Provider ClassesManaged Provider Classes

Three different sets of classes for accessing:Three different sets of classes for accessing: SQL Server databases (SQL Server databases (System.Data.SqlClientSystem.Data.SqlClient)) OLE (Object linking and embedding) databases (OLE (Object linking and embedding) databases (System.System.Data.OleDb)Data.OleDb)

e.g. Access, Oraclee.g. Access, Oracle ODBC (Open DataBase Connectivity) databases (System.Data.Odbc) ODBC (Open DataBase Connectivity) databases (System.Data.Odbc)

e.g. all major databases but slower than OLE DBe.g. all major databases but slower than OLE DB Includes following classes:Includes following classes:

ConnectionConnection CommandCommand ParameterParameter ParameterCollectionParameterCollection DataReaderDataReader DataAdapterDataAdapter CommandBuilderCommandBuilder TransactionTransaction

Names follow simple pattern: Names follow simple pattern: e.g. SqlConnection, OleDbConnection, OdbcConnectione.g. SqlConnection, OleDbConnection, OdbcConnection

Page 18: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

ADO.NET:ADO.NET:A simple exampleA simple example

using System;using System;using System.Data;using System.Data;using System.Data.OleDb;using System.Data.OleDb;

class class SimpleExampleSimpleExample { {public static void Main() {public static void Main() {…… }}

}}

Page 19: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

ADO.NET:ADO.NET:OleDbConnectionOleDbConnection

string connString = "Provider=Microsoft.Jet.OLEDB.4.0;string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Data Source=C:\\Test Files\\Sample.mdbC:\\Test Files\\Sample.mdb;;User Id=admin;Password=;";User Id=admin;Password=;";

OleDbConnection OleDbConnection conn conn = new OleDbConnection(connString); = new OleDbConnection(connString); ……conn.Open(); conn.Open(); ……conn.Close();conn.Close();

Connection string specifies server, database, user & password (if needed)Connection string specifies server, database, user & password (if needed) Close connections are added to a pool to be reused if the same connection Close connections are added to a pool to be reused if the same connection

string is used. Saves much time in comparison to establishing a new string is used. Saves much time in comparison to establishing a new connectionconnection

Public PropertiesPublic Properties ConnectionString, ConnectionTimeout, Database, DatabaseSource, ConnectionString, ConnectionTimeout, Database, DatabaseSource,

ServerVersion, State, WorkstationIdServerVersion, State, WorkstationId Public MethodsPublic Methods

BeginTransaction()BeginTransaction(), , ChangeDatabase()ChangeDatabase(), , Close()Close(), , CreateCommand()CreateCommand(), , Open() Open()

Page 20: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

ADO.NET:ADO.NET:OleDbCommandOleDbCommand

OleDbCommand cmd = new OleDbCommand();OleDbCommand cmd = new OleDbCommand();cmd.Connection = conn;cmd.Connection = conn;cmd.Transaction = trans;cmd.Transaction = trans;cmd.CommandText =cmd.CommandText = “ “““DELETE FROM Students“;DELETE FROM Students“;

Or:Or:OleDbCommand cmd = OleDbCommand cmd =

new OleDbCommand(“new OleDbCommand(“DELETE FROM Students“,DELETE FROM Students“,connconn, , transtrans);); One can also be created by executing CreateCommand() on a Connection One can also be created by executing CreateCommand() on a Connection

instance (matter of taste)instance (matter of taste) Needs an open connection before executionNeeds an open connection before execution

Public PropertiesPublic Properties CommandText, CommandTimeout, CommandType, Connection, CommandText, CommandTimeout, CommandType, Connection,

DesignTimeVisible, Parameters, Transaction, UpdatedRowSourceDesignTimeVisible, Parameters, Transaction, UpdatedRowSource Public MethodsPublic Methods

Cancel(), Cancel(), CreateParameter()CreateParameter(), , ExecuteNonQuery()ExecuteNonQuery(), , ExecuteReader()ExecuteReader(), , ExecuteScalar()ExecuteScalar(), , ExecuteXmlReader()ExecuteXmlReader(), , Prepare()Prepare(), , ResetCommandTimeout() ResetCommandTimeout()

Page 21: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

ADO.NET:ADO.NET:ExecuteNonQuery()ExecuteNonQuery()

cmd.cmd.ExecuteNonQuery()ExecuteNonQuery()ororint rowsAffected = cmd.int rowsAffected = cmd.ExecuteNonQuery()ExecuteNonQuery();;

RReturneturns s the number of database rows affected the number of database rows affected by the command, if any.by the command, if any.

Can be used for Can be used for SQL INSERT, UPDATE, and SQL INSERT, UPDATE, and DELETE statementsDELETE statements, , stored procedures that stored procedures that don't return a value or Data Definition Language don't return a value or Data Definition Language (DDL) statements such as CREATE TABLE and (DDL) statements such as CREATE TABLE and CREATE INDEXCREATE INDEX

Page 22: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

ADO.NET:ADO.NET:ExecuteExecuteReaderReader()()

OleDbDataOleDbDataReader Reader myReadermyReader = = mySqlCommand.ExecuteReader(); mySqlCommand.ExecuteReader();

Requires an open connectionRequires an open connection You need to close the reader as soon as you’re You need to close the reader as soon as you’re

done to release the resourcesdone to release the resources

The execution is parametrized. Possible values:The execution is parametrized. Possible values: CloseConnection, Default, KeyInfo, CloseConnection, Default, KeyInfo, SchemaOnly, SequentialAccess, SingleResult, SchemaOnly, SequentialAccess, SingleResult, SingleRowSingleRowUsually issued without any (default)Usually issued without any (default)

Page 23: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

ADO.NET:ADO.NET:OleDbDataReaderOleDbDataReader

while (while (mymyReader.Read())Reader.Read()) {{Console.WriteLine(Console.WriteLine(mymyReader[“Reader[“FirstNameFirstName"]);"]);CConsole.WriteLine(onsole.WriteLine(mymyReaderReader[0[0]); ]);

}} Second way is faster but depends on schema or querySecond way is faster but depends on schema or query Middle solution: Middle solution: myReader[ myReader.GetOrdinal(“FirstName”) ]myReader[ myReader.GetOrdinal(“FirstName”) ] IsDBNullIsDBNull()() should be used to avoid an OleDbExceptionshould be used to avoid an OleDbException

Public PropertiesPublic Properties Depth, FieldCount, IsClosed, RecordsAffectedDepth, FieldCount, IsClosed, RecordsAffected

Public MethodsPublic Methods GetBoolean(), GetByte(), GetBytes(), GetChar(), GetChars(), GetBoolean(), GetByte(), GetBytes(), GetChar(), GetChars(),

GetDataTypeName(), GetDateTime(), GetDecimal(), GetDouble(), GetDataTypeName(), GetDateTime(), GetDecimal(), GetDouble(), GetFieldType(), GetFloat(), GetGuid(), GetInt16(), GetInt32(), GetInt64(), GetFieldType(), GetFloat(), GetGuid(), GetInt16(), GetInt32(), GetInt64(), GetName(), GetName(), GetOrdinal()GetOrdinal(), GetSchemaTable(), GetSqlBinary(), , GetSchemaTable(), GetSqlBinary(), GetSqlBoolean(), GetSqlByte(), GetSqlDateTime(), GetSqlDecimal(), GetSqlBoolean(), GetSqlByte(), GetSqlDateTime(), GetSqlDecimal(), GetSqlDouble(), GetSqlGuid(), GetSqlInt16(), GetSqlInt32(), GetSqlInt64(), GetSqlDouble(), GetSqlGuid(), GetSqlInt16(), GetSqlInt32(), GetSqlInt64(), GetSqlMoney(), GetSqlSingle(), GetSqlString(), GetSqlValue(), GetSqlValues(), GetSqlMoney(), GetSqlSingle(), GetSqlString(), GetSqlValue(), GetSqlValues(), GetString(), GetValue(), GetValues(), GetString(), GetValue(), GetValues(), IsDBNull(),IsDBNull(), NextResult(),NextResult(), Read()Read()

Page 24: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

ADO.NET:ADO.NET:OleDbDataReader (cont.)OleDbDataReader (cont.)

OleDbOleDbCommand Command cmdcmd = = OleDb.OleDb.Connection.CreateCommand(); Connection.CreateCommand(); ccmd.CommandText = "SELECT md.CommandText = "SELECT * FROM Students; * FROM Students; SELECT SELECT * * FROM Faculty;”FROM Faculty;”; ; ……OleDbDataReader myReader = cmd.ExecuteReader();OleDbDataReader myReader = cmd.ExecuteReader();……do { do {

while (while (myRmyReader.Read()) {eader.Read()) {Console.WriteLine(Console.WriteLine(..);..);

……} }

} while (myReader.NextResult()); } while (myReader.NextResult()); The outer loop iterates through all result sets (even empty)The outer loop iterates through all result sets (even empty) The inner loop processed only the non-empty result setsThe inner loop processed only the non-empty result sets Do…while instead of While because NextResult() advances to next Do…while instead of While because NextResult() advances to next

result setresult set

Page 25: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

ADO.NET:ADO.NET:OleDbTransactionOleDbTransaction

OleDbTransaction trans = conn.BeginTransaction();OleDbTransaction trans = conn.BeginTransaction();……cmd.Transaction = trans;cmd.Transaction = trans;……cmd.ExecuteNonQuery();cmd.ExecuteNonQuery();……trans.Commit();trans.Commit();ORORtrans.Rollback();trans.Rollback();

Either all actions succeed and become persistent or (at least) one fails and Either all actions succeed and become persistent or (at least) one fails and the rest get canceledthe rest get canceled

try {try {……

} catch (Exception ex) {} catch (Exception ex) {if (trans != null)if (trans != null)

trans.Rollback();trans.Rollback();Console.Out.WriteLine("Exception: " + ex.Message);Console.Out.WriteLine("Exception: " + ex.Message);Console.Out.WriteLine(ex.StackTrace);Console.Out.WriteLine(ex.StackTrace);

}}

Page 26: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

ADO.NET:ADO.NET:DataSet objectsDataSet objects

Generic classes, independent of databaseGeneric classes, independent of databaseMake local copy, modify and push Make local copy, modify and push

changes back to the databasechanges back to the databaseBeforeBefore you populate a DataSet you first you populate a DataSet you first

need a Connection, a Command, and a need a Connection, a Command, and a DataAdapterDataAdapter

Used for random access to data (not Used for random access to data (not forward-only) and disconnected workforward-only) and disconnected work

Page 27: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

C# Trip is overC# Trip is over

There’s only one way to learn a programming language There’s only one way to learn a programming language well: experience through trial-and-errorwell: experience through trial-and-error

One day you’ll hear yourself saying “Oh, I’ve had that One day you’ll hear yourself saying “Oh, I’ve had that same problem before and…”same problem before and…”

Some tipsSome tips spend time programmingspend time programming try things you don’t know how to do yettry things you don’t know how to do yet question the source of your errorsquestion the source of your errors try to do it efficiently and elegantlytry to do it efficiently and elegantly Don’t neglect all experience already made publicDon’t neglect all experience already made public The .NET Framework provides classes for most of the common The .NET Framework provides classes for most of the common

tasks but they’re not always obvious. Five minutes of searching tasks but they’re not always obvious. Five minutes of searching in the help files can save you from reinventing the wheelin the help files can save you from reinventing the wheel

Page 28: CSci485 C# Lecture 1 - Antonios Daskos An Introduction to C# and Database Programming with ADO.NET Antonios Daskos.

CSci485 C# Lecture 1 - Antonios DaskosCSci485 C# Lecture 1 - Antonios Daskos

ReferencesReferences

““Mastering C# Database Programming Mastering C# Database Programming Jason Price, Sybex, 2003Jason Price, Sybex, 2003

MSDNMSDN