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

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Introduction to ASP.NET.
Advertisements

Computer and Programming
Introduction to Database Processing with ADO.NET.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
1 ADO.NET. 2.NET Framework Data Namespaces System.Data –Base set of classes and interfaces for ADO.NET System.Data.Common –Classes shared by the.NET Data.
Introduction to the C# Programming Language for the VB Programmer.
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
ASP.NET Programming with C# and SQL Server First Edition
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Chapter 12 Database Connectivity with ASP.NET JavaScript, Third Edition.
In C# program Before you can start using the ODBC class definitions, you will need to include the right module. using System.Data.Odbc; // ODBC definitions.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Overview of Microsoft.Net and Vb.Net ITSE 2349 Spring 2002 Material from Microsoft.Net an Overview for ACC faculty by Stuart Laughton and Introduction.
1 Chapter One A First Program Using C#. 2 Objectives Learn about programming tasks Learn object-oriented programming concepts Learn about the C# programming.
A First Program Using C#
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
11 Getting Started with C# Chapter Objectives You will be able to: 1. Say in general terms how C# differs from C. 2. Create, compile, and run a.
Introduction to .NET Framework
Creating and Running Your First C# Program Svetlin Nakov Telerik Corporation
ADO.NET A2 Teacher Up skilling LECTURE 3. What’s to come today? ADO.NET What is ADO.NET? ADO.NET Objects SqlConnection SqlCommand SqlDataReader DataSet.
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
Needs for Accessing Database To make your web site more dynamic and maintainable, you can display information on your web pages that are retrieved from.
CS795/895: Introduction. Topics Distributed Systems –Availability –Performance –Web Services Security –Authentication –Authorization –Confidentiality.
Databases and Data Access  Introduction to ADO.NET  ADO.NET objects  ADP.NET namespaces  Differences between ADO and ADO.NET.
ADO.Net CS795. What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.Net.
.NET Data Access and Manipulation ADO.NET. Overview What is ADO.NET? Disconnected vs. connected data access models ADO.NET Architecture ADO.NET Core Objects.
Java Programming, Second Edition Chapter One Creating Your First Java Program.
 It is the primary data access model for.Net applications  Next version of ADO  Can be divided into two parts ◦ Providers ◦ DataSets  Resides in System.Data.
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ADO.Net Basics Ruwan Wijesinghe Trainer.
Introduction to Exception Handling and Defensive Programming.
Applied Computing Technology Laboratory QuickStart C# Learning to Program in C# Amy Roberge & John Linehan November 7, 2005.
Module 7: Accessing Data by Using ADO.NET
Christopher M. Pascucci.NET Programming: Databases & ADO.NET.
Presented by Joseph J. Sarna Jr. JJS Systems, LLC
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
An Introduction to ADO.Net Marmagna Desai.NET Seminar, Fall-2003.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Module 3: Performing Connected Database Operations.
ADO.NET connections1 Connecting to SQL Server and Oracle.
 It is the primary data access model for.Net applications  Next version of ADO  Can be divided into two parts ◦ Providers ◦ DataSets  Resides in System.Data.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
1 11/10/05CS360 Windows Programming ADO.NET. 2 11/10/05CS360 Windows Programming ADO.NET  Behind every great application is a database manager o Amazon.
JDS – VB.NET Skill Session Fall 2004 Presented by YUHAO LIN.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
ADO.Net CS795. What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.Net.
HNDIT Rapid Application Development
Object Oriented Software Development 4. C# data types, objects and references.
Database Connectivity with ASP.NET. 2 Introduction Web pages commonly used to: –Gather information stored on a Web server database Most server-side scripting.
Module 4 Introduction ADO.NET.
INTRODUCTION CHAPTER #1 Visual Basic.NET. VB.Net General features It is an object oriented language  In the past VB had objects but focus was not placed.
Active Data Objects Using.Net ADO.Net Farooq Ahmed Amna Umber Summayya Shehzad.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Session 02 Module 3: Statements and Operators Module 4: Programming constructs Module 5: Arrays.
Introduction to Database C# MySQL onnect-C-to-MySQL 1.
ADO .NET from. ADO .NET from “ADO .Net” Evolution/History of ADO.NET MICROSOFT .NET “ADO .Net” Evolution/History of ADO.NET History: Most applications.
.NET Data Access and Manipulation
ASP.NET Programming with C# and SQL Server First Edition
Introduction to Database Processing with ADO.NET
Introduction to Database Processing with ADO.NET
ADO.NET Framework.
Programming the Web Using ASP.Net
Lecture 6 VB.Net SQL Server.
Active Data Objects Binding ASP.NET Controls to Data
Tonga Institute of Higher Education
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
Chapter 8 Advanced SQL.
Active Data Objects Binding ASP.NET Controls to Data
M S COLLEGE OF ART’S, COMM., SCI. & BMS Advance Web Programming
IS 135 Business Programming
Presentation transcript:

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

CSci485 C# Lecture 1 - Antonios Daskos Outline Object Oriented Programming (OOP) Object Oriented Programming (OOP).NET Introduction.NET Introduction C# basics C# basics VS.NET VS.NET Databases with C# (ADO.NET) Databases with C# (ADO.NET)

CSci485 C# Lecture 1 - Antonios Daskos.NET Framework Development languages Development languages C++, C#, VB, J#, JScript, Python, Perl, Fortran, S#, Cobol, ASP, XSLT, Eiffel… More than 20 languages C++, C#, VB, J#, JScript, Python, Perl, Fortran, S#, Cobol, ASP, XSLT, Eiffel… More than 20 languages Integrated Development Environments (IDEs) Integrated Development Environments (IDEs) Visual Studio.NET, Mono Project Visual Studio.NET, Mono Project Common Language Infrastructure (CLI) and Common Language Runtime (CLR) Common Language Infrastructure (CLI) and Common Language Runtime (CLR) A specification and its implementation A specification and its implementation Provides a common managed runtime for all supported languages Provides a common managed runtime for all supported languages Common Type System (CTS) Common Type System (CTS)

CSci485 C# Lecture 1 - Antonios Daskos.NET Framework (cont.) IL (Intermediate Language) and Just In Time (JIT) Compilation IL (Intermediate Language) and Just In Time (JIT) Compilation Language independence Language independence Abstraction similar to Java’s Virtual Machine only more generic Abstraction similar to Java’s Virtual Machine only more generic Portability Portability Framework Base Class Library Framework Base Class Library Namespaces Namespaces Memory Management and Garbage Collection Memory Management and Garbage Collection Plethora of documentation, examples or tips Plethora of documentation, examples or tips MSDN: provided to you; also available online at MSDN: provided to you; also available online at Programming web sites and forums (most of the times your question has been answered before – needs patience and good search keywords) Programming web sites and forums (most of the times your question has been answered before – needs patience and good search keywords) Search engines Search engines Books, magazines, newsgroups… Books, magazines, newsgroups…

CSci485 C# Lecture 1 - Antonios Daskos OOP: a software construction paradigm Objects Objects Abstract concepts, basic entities that describe internal information (variables) and the means to access it, change its state, perform actions (functions) Abstract concepts, basic entities that describe internal information (variables) and the means to access it, change its state, perform actions (functions) In C# (like Java and most OOP languages) everything is an object In C# (like Java and most OOP languages) everything is an object Classes Classes 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 instances a blueprint for instances Instances Instances Building blocks of the code Building blocks of the code Allocated in memory sharing the code but not the data Allocated in memory sharing the code but not the data Methods / Fields Methods / Fields Primary mechanisms (code common to all instances of a class) and data variables Primary mechanisms (code common to all instances of a class) and data variables Static parts: belong to a class, accessible and shared by all instances Static parts: belong to a class, accessible and shared by all instances Scope Scope

CSci485 C# Lecture 1 - Antonios Daskos OOP: a software construction paradigm (cont.) Abstraction Abstraction Inheritance Inheritance Polymorphism Polymorphism Encapsulation Encapsulation Simple example (don’t worry about all the new things): … public class MyNumber { int val = 20; public int value() { return val; } public int increase(int how_much) { val += how_much; //val = val + how much; return val; } } … MyNumber m = new MyNumber(); int l = m.value(); // l will be 20 int k = m.increase(12); // k will be 32 Simple example (don’t worry about all the new things): … public class MyNumber { int val = 20; public int value() { return val; } public int increase(int how_much) { val += how_much; //val = val + how much; return val; } } … MyNumber m = new MyNumber(); int l = m.value(); // l will be 20 int k = m.increase(12); // k will be 32

CSci485 C# Lecture 1 - Antonios Daskos C# Basics Case sensitive Case sensitive Common data types (primitives): Common data types (primitives): bool, byte, short/int/long, float/double, char/string bool, byte, short/int/long, float/double, char/string Conversion Conversion implicitly implicitly float f = 56; float f = 56; by casting by casting int i = (int)5.6; int i = (int)5.6; with convert class with convert class int i = System.Convert.ToInt32(3.25d); int i = System.Convert.ToInt32(3.25d); provided methods provided methods string s = (5.25).ToString(); //a bit uncommon but it works string s = (5.25).ToString(); //a bit uncommon but it works

CSci485 C# Lecture 1 - Antonios Daskos C# Basics II Operators: Operators: +,-,*,/,% +,-,*,/,% &,|,…, &&, ||, … &,|,…, &&, ||, … ++,--… ++,--…, ==,…, ==,… ? Decision making: Decision making: if...then…else if...then…else do…while, while, for do…while, while, for Foreach e.g foreach (int i in list_of_ints) { … } Foreach e.g foreach (int i in list_of_ints) { … } switch (more strict than c++/java) switch (more strict than c++/java) Declarations and scope Declarations and scope Comments like c++ (try Ctrl-K-C and Ctrl-K-U for mass commenting ;-) Comments like c++ (try Ctrl-K-C and Ctrl-K-U for mass commenting ;-)

CSci485 C# Lecture 1 - Antonios Daskos C# Classes Everything is a class derived from class Object Everything is a class derived from class Object Namespaces to avoid confusion Namespaces to avoid confusion Create new instances with keyword new string s1 = new string(‘T’,3); //s1 = “TTT” Create new instances with keyword new string s1 = new string(‘T’,3); //s1 = “TTT” Reference their methods with dot (.) string s2 = s2.ToLower (); //s2 = “ttt” Reference their methods with dot (.) string s2 = s2.ToLower (); //s2 = “ttt” Parameters inside brackets as in the constructor Parameters inside brackets as in the constructor Public/private, static, final Public/private, static, final Try looking at existing examples all around if unfamiliar with syntax; may find it easier to edit existing code at first Try looking at existing examples all around if unfamiliar with syntax; may find it easier to edit existing code at first

CSci485 C# Lecture 1 - Antonios Daskos C#: Hello world! using System; class MyApp { static void Main () { Console.WriteLine ("Hello world!"); } } using System; class MyApp { static void Main () { Console.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.cs Write 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\v \csc.exe in my machine C:\WINDOWS\Microsoft.NET\Framework\v \csc.exe in my machine Add it to path for convenience Add it to path for convenience Run the produced executable e.g. MyApp.exe Run the produced executable e.g. MyApp.exe

CSci485 C# Lecture 1 - Antonios Daskos C#: Useful libraries System.Math class e.g. double d = Math.Pow(5,3); //d = 5 3 System.Math class e.g. double d = Math.Pow(5,3); //d = 5 3 System.Collections class e.g.ArrayList, Hashtable, Stack, SortedList, etc. ArrayList a = new ArraList(); a.Add(5); a.Add(6.7); int i = (int)a[0]; double d = (double)a[1]; System.Collections class e.g.ArrayList, Hashtable, Stack, SortedList, etc. ArrayList a = new ArraList(); a.Add(5); a.Add(6.7); int i = (int)a[0]; 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) Threading Threading

CSci485 C# Lecture 1 - Antonios Daskos C#: Console Two very common functions for console applications: Two very common functions for console applications: Write(…): Writes the specified information to the standard output stream Write(…): Writes the specified information to the standard output stream WriteLine(…): Like Write() only followed by the current line terminator WriteLine(…): Like Write() only followed by the current line terminator Read(…): Reads the next character from the standard input stream Read(…): Reads the next character from the standard input stream ReadLine(…): Reads the next line of characters from the standard input stream ReadLine(…): Reads the next line of characters from the standard input stream To prevent the execution of a program from terminating when done you can add all the code in a try-block with a Console.ReadLine() in the finally-block (see next slide for exception handling) To prevent the execution of a program from terminating when done you can add all the code in a try-block with a Console.ReadLine() in the finally-block (see next slide for exception handling)

CSci485 C# Lecture 1 - Antonios Daskos C#: Exceptions try { …//code that can generate errors //and throw exceptions } catch (ExceptionType1 ex1) { … //code to handle type1 exceptions } catch (ExceptionType2 ex2) { … //code to handle type1 exceptions } catch { …//code to handle the rest of the exceptions } finally { …//code to be executed regardless } try { …//code that can generate errors //and throw exceptions } catch (ExceptionType1 ex1) { … //code to handle type1 exceptions } catch (ExceptionType2 ex2) { … //code to handle type1 exceptions } catch { …//code to handle the rest of the exceptions } finally { …//code to be executed regardless }

CSci485 C# Lecture 1 - Antonios Daskos Visual Studio.NET Allows for all sorts of projects (Windows apps, ASP projects, Web Services, etc) Allows for all sorts of projects (Windows apps, ASP projects, Web Services, etc) New C# project: New C# project: File  New  Project File  New  Project Choose “Visual C# Projects” and Choose “Visual C# Projects” and Console Application for simple console programs Console Application for simple console programs Windows Application for a project with GUI Windows Application for a project with GUI Choose project’s name and path Choose project’s name and path Possibly the project will contain VS.NET generated code Possibly the project will contain VS.NET generated code

CSci485 C# Lecture 1 - Antonios Daskos Visual Studio.NET (cont.) Colors help reading your code and indicate simple errors real time Colors help reading your code and indicate simple errors real time Compiling or running the code will indicate all compile time errors. Runtime errors might still occur Compiling or running the code will indicate all compile time errors. Runtime errors might still occur Debugger, code tracing, breakpoints and watches are invaluable tools – learn the shortcuts and how to use them Debugger, code tracing, breakpoints and watches are invaluable tools – learn the shortcuts and how to use them Intellisense Intellisense Makes typing faster Makes typing faster No need to remember exact function names No need to remember exact function names Demonstrates parameters and short descriptions Demonstrates parameters and short descriptions Reveals an object’s methods – you can do miracles by just a little guessing Reveals an object’s methods – you can do miracles by just a little guessing

CSci485 C# Lecture 1 - Antonios Daskos ADO.NET Two sets of classes: Two sets of classes: Managed Provider Classes Managed Provider Classes Connecting to the database Connecting to the database Data manipulation through SQL Data manipulation through SQL Forward-only reading of data Forward-only reading of data Generic Data Classes Generic Data Classes Offline data managing Offline data managing Non-sequential access and editing of data by C# code Non-sequential access and editing of data by C# code

CSci485 C# Lecture 1 - Antonios Daskos ADO.NET: Managed Provider Classes Three different sets of classes for accessing: Three different sets of classes for accessing: SQL Server databases (System.Data.SqlClient) SQL Server databases (System.Data.SqlClient) OLE (Object linking and embedding) databases (System.Data.OleDb) e.g. Access, Oracle OLE (Object linking and embedding) databases (System.Data.OleDb) e.g. Access, Oracle ODBC (Open DataBase Connectivity) databases (System.Data.Odbc) e.g. all major databases but slower than OLE DB ODBC (Open DataBase Connectivity) databases (System.Data.Odbc) e.g. all major databases but slower than OLE DB Includes following classes: Includes following classes: Connection Connection Command Command Parameter Parameter ParameterCollection ParameterCollection DataReader DataReader DataAdapter DataAdapter CommandBuilder CommandBuilder Transaction Transaction Names follow simple pattern: e.g. SqlConnection, OleDbConnection, OdbcConnection Names follow simple pattern: e.g. SqlConnection, OleDbConnection, OdbcConnection

CSci485 C# Lecture 1 - Antonios Daskos ADO.NET: A simple example using System; using System.Data; using System.Data.OleDb; class SimpleExample { public static void Main() { … } } using System; using System.Data; using System.Data.OleDb; class SimpleExample { public static void Main() { … } }

CSci485 C# Lecture 1 - Antonios Daskos ADO.NET: OleDbConnection string connString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\Test Files\\Sample.mdb; User Id=admin;Password=;"; OleDbConnection conn = new OleDbConnection(connString); … conn.Open(); … conn.Close(); string connString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\Test Files\\Sample.mdb; User Id=admin;Password=;"; OleDbConnection conn = new OleDbConnection(connString); … conn.Open(); … 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 string is used. Saves much time in comparison to establishing a new 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 connection Public Properties Public Properties ConnectionString, ConnectionTimeout, Database, DatabaseSource, ServerVersion, State, WorkstationId ConnectionString, ConnectionTimeout, Database, DatabaseSource, ServerVersion, State, WorkstationId Public Methods Public Methods BeginTransaction(), ChangeDatabase(), Close(), CreateCommand(), Open() BeginTransaction(), ChangeDatabase(), Close(), CreateCommand(), Open()

CSci485 C# Lecture 1 - Antonios Daskos ADO.NET: OleDbCommand OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn; cmd.Transaction = trans; cmd.CommandText = ““DELETE FROM Students“; OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn; cmd.Transaction = trans; cmd.CommandText = ““DELETE FROM Students“; Or: OleDbCommand cmd = new OleDbCommand(“DELETE FROM Students“,conn, trans); Or: OleDbCommand cmd = new OleDbCommand(“DELETE FROM Students“,conn, trans); One can also be created by executing CreateCommand() on a Connection instance (matter of taste) One can also be created by executing CreateCommand() on a Connection instance (matter of taste) Needs an open connection before execution Needs an open connection before execution Public Properties Public Properties CommandText, CommandTimeout, CommandType, Connection, DesignTimeVisible, Parameters, Transaction, UpdatedRowSource CommandText, CommandTimeout, CommandType, Connection, DesignTimeVisible, Parameters, Transaction, UpdatedRowSource Public Methods Public Methods Cancel(), CreateParameter(), ExecuteNonQuery(), ExecuteReader(), ExecuteScalar(), ExecuteXmlReader(), Prepare(), ResetCommandTimeout() Cancel(), CreateParameter(), ExecuteNonQuery(), ExecuteReader(), ExecuteScalar(), ExecuteXmlReader(), Prepare(), ResetCommandTimeout()

CSci485 C# Lecture 1 - Antonios Daskos ADO.NET: ExecuteNonQuery() cmd.ExecuteNonQuery() or int rowsAffected = cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery() or int rowsAffected = cmd.ExecuteNonQuery(); Returns the number of database rows affected by the command, if any. Returns the number of database rows affected by the command, if any. Can be used for SQL INSERT, UPDATE, and DELETE statements, stored procedures that don't return a value or Data Definition Language (DDL) statements such as CREATE TABLE and CREATE INDEX Can be used for SQL INSERT, UPDATE, and DELETE statements, stored procedures that don't return a value or Data Definition Language (DDL) statements such as CREATE TABLE and CREATE INDEX

CSci485 C# Lecture 1 - Antonios Daskos ADO.NET: ExecuteReader() OleDbDataReader myReader = mySqlCommand.ExecuteReader(); OleDbDataReader myReader = mySqlCommand.ExecuteReader(); Requires an open connection Requires an open connection You need to close the reader as soon as you’re done to release the resources You need to close the reader as soon as you’re done to release the resources The execution is parametrized. Possible values: CloseConnection, Default, KeyInfo, SchemaOnly, SequentialAccess, SingleResult, SingleRow Usually issued without any (default) The execution is parametrized. Possible values: CloseConnection, Default, KeyInfo, SchemaOnly, SequentialAccess, SingleResult, SingleRow Usually issued without any (default)

CSci485 C# Lecture 1 - Antonios Daskos ADO.NET: OleDbDataReader while (myReader.Read()) { Console.WriteLine(myReader[“FirstName"]); Console.WriteLine(myReader[0]); } while (myReader.Read()) { Console.WriteLine(myReader[“FirstName"]); Console.WriteLine(myReader[0]); } Second way is faster but depends on schema or query Second way is faster but depends on schema or query Middle solution: myReader[ myReader.GetOrdinal(“FirstName”) ] Middle solution: myReader[ myReader.GetOrdinal(“FirstName”) ] IsDBNull() should be used to avoid an OleDbException IsDBNull() should be used to avoid an OleDbException Public Properties Public Properties Depth, FieldCount, IsClosed, RecordsAffected Depth, FieldCount, IsClosed, RecordsAffected Public Methods Public Methods GetBoolean(), GetByte(), GetBytes(), GetChar(), GetChars(), GetDataTypeName(), GetDateTime(), GetDecimal(), GetDouble(), GetFieldType(), GetFloat(), GetGuid(), GetInt16(), GetInt32(), GetInt64(), GetName(), GetOrdinal(), GetSchemaTable(), GetSqlBinary(), GetSqlBoolean(), GetSqlByte(), GetSqlDateTime(), GetSqlDecimal(), GetSqlDouble(), GetSqlGuid(), GetSqlInt16(), GetSqlInt32(), GetSqlInt64(), GetSqlMoney(), GetSqlSingle(), GetSqlString(), GetSqlValue(), GetSqlValues(), GetString(), GetValue(), GetValues(), IsDBNull(), NextResult(), Read() GetBoolean(), GetByte(), GetBytes(), GetChar(), GetChars(), GetDataTypeName(), GetDateTime(), GetDecimal(), GetDouble(), GetFieldType(), GetFloat(), GetGuid(), GetInt16(), GetInt32(), GetInt64(), GetName(), GetOrdinal(), GetSchemaTable(), GetSqlBinary(), GetSqlBoolean(), GetSqlByte(), GetSqlDateTime(), GetSqlDecimal(), GetSqlDouble(), GetSqlGuid(), GetSqlInt16(), GetSqlInt32(), GetSqlInt64(), GetSqlMoney(), GetSqlSingle(), GetSqlString(), GetSqlValue(), GetSqlValues(), GetString(), GetValue(), GetValues(), IsDBNull(), NextResult(), Read()

CSci485 C# Lecture 1 - Antonios Daskos ADO.NET: OleDbDataReader (cont.) OleDbCommand cmd = OleDb.Connection.CreateCommand(); cmd.CommandText = "SELECT * FROM Students; SELECT * FROM Faculty;”; … OleDbDataReader myReader = cmd.ExecuteReader(); … do { while (myReader.Read()) { Console.WriteLine(..); … } } while (myReader.NextResult()); OleDbCommand cmd = OleDb.Connection.CreateCommand(); cmd.CommandText = "SELECT * FROM Students; SELECT * FROM Faculty;”; … OleDbDataReader myReader = cmd.ExecuteReader(); … do { while (myReader.Read()) { Console.WriteLine(..); … } } 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 sets The inner loop processed only the non-empty result sets Do…while instead of While because NextResult() advances to next result set Do…while instead of While because NextResult() advances to next result set

CSci485 C# Lecture 1 - Antonios Daskos ADO.NET: OleDbTransaction OleDbTransaction trans = conn.BeginTransaction(); … cmd.Transaction = trans; … cmd.ExecuteNonQuery(); … trans.Commit(); OR trans.Rollback(); OleDbTransaction trans = conn.BeginTransaction(); … cmd.Transaction = trans; … cmd.ExecuteNonQuery(); … trans.Commit(); OR trans.Rollback(); Either all actions succeed and become persistent or (at least) one fails and the rest get canceled Either all actions succeed and become persistent or (at least) one fails and the rest get canceled try { … } catch (Exception ex) { if (trans != null) trans.Rollback(); Console.Out.WriteLine("Exception: " + ex.Message); Console.Out.WriteLine(ex.StackTrace); } try { … } catch (Exception ex) { if (trans != null) trans.Rollback(); Console.Out.WriteLine("Exception: " + ex.Message); Console.Out.WriteLine(ex.StackTrace); }

CSci485 C# Lecture 1 - Antonios Daskos ADO.NET: DataSet objects Generic classes, independent of database Generic classes, independent of database Make local copy, modify and push changes back to the database Make local copy, modify and push changes back to the database Before you populate a DataSet you first need a Connection, a Command, and a DataAdapter Before you populate a DataSet you first need a Connection, a Command, and a DataAdapter Used for random access to data (not forward-only) and disconnected work Used for random access to data (not forward-only) and disconnected work

CSci485 C# Lecture 1 - Antonios Daskos C# Trip is over There’s only one way to learn a programming language well: experience through trial-and-error There’s only one way to learn a programming language well: experience through trial-and-error One day you’ll hear yourself saying “Oh, I’ve had that same problem before and…” One day you’ll hear yourself saying “Oh, I’ve had that same problem before and…” Some tips Some tips spend time programming spend time programming try things you don’t know how to do yet try things you don’t know how to do yet question the source of your errors question the source of your errors try to do it efficiently and elegantly try to do it efficiently and elegantly Don’t neglect all experience already made public Don’t neglect all experience already made public The.NET Framework provides classes for most of the common tasks but they’re not always obvious. Five minutes of searching in the help files can save you from reinventing the wheel The.NET Framework provides classes for most of the common tasks but they’re not always obvious. Five minutes of searching in the help files can save you from reinventing the wheel

CSci485 C# Lecture 1 - Antonios Daskos References “Mastering C# Database Programming Jason Price, Sybex, 2003 “Mastering C# Database Programming Jason Price, Sybex, 2003 MSDN MSDN