Sie sind auf Seite 1von 7

Data Access Programming applications can access data from a variety of data sources o in-memory data structures (e.g.

., variables, arrays, lists, etc.) o data files in various formats (e.g., plain text, formatted text, binary, spreadsheets, XML, etc.) o databases (legacy, RDBMS, ORDBMS) o data services (e.g., applications, remote data objects, web services, etc.) o hardware devices the nature of the data source dictates how data is accessed and what can be done with the data o direct manipulation, library routine calls, SQL queries, method calls, register-based I/O, memory-mapped I/O, etc. o sequential access, random access o field-oriented access, line-oriented access, record-oriented access, block-oriented access o read-only access, write-only access, read-write access o online access, offline access, local access, remote access software development environments provide (or provide support for) some data access technology or standard o the standard defines data access components which specify how data can be accessed/manipulated programmatically in the environment library routines in traditional environments library objects in OO environments (typically as abstract base classes and/or interfaces) o specific data source vendors (e.g., MySQL, Oracle, SQL Server, etc.) define data providers (a.k.a. drivers) compatible with the standard; these drivers implement the functionality specified by the standard, as applied to the specific backend technology o the developers then make use of the functionality provided by the data access components, and the data providers map the operations to the specific backend data source, thus giving the developers a consistent interface to data access/manipulation, without having to be concerned about all the specific details of the backend technology o common data access technologies: Data Access Objects (DAO) Open Database Connectivity (ODBC) ActiveX Data Objects (ADO) Object Linking and Embedding - Database (OLEDB) Java Database Connectivity (JDBC)

ADO.NET data access architecture for the .NET Framework software components included in the Microsoft .NET Framework BCL which can be used by programmers to access data and data services allows access to relational or non-relational data sources architecture:

o .NET Framework Data Provider Connection used to establish a connection to a data source Command used to issue operations to the data source (retrieve data, manipulate data, run stored procedures, send or retrieve parameter information, etc.) Parameter used to provide arguments to commands DataReader used to provide record-oriented read-only, forwardonly access to a record set returned by data retrieval operation DataAdapter used as a bridge to transfer data between a data source and a data set Microsoft .NET Framework comes bundled with data providers for SQL Server, Oracle, OLEDB, and ODBC; third-party vendor providers are also available (e.g., Connector/NET for MySQL) o DataSet designed for data access independent of any data source represents data as a simple, in-memory relational database can be used with multiple or differing data sources, can save its data to or be populated from XML, used to manage data local to an application, provide for disconnected access to data, etc.

using System; using System.Data.OleDb; namespace DataAccessSample { class Program { static void Main(string[] args) { OleDbConnectionStringBuilder ocsb; OleDbConnection conn; OleDbCommand cmd; OleDbDataReader reader; OleDbParameter p, q; ocsb = new OleDbConnectionStringBuilder(); ocsb["Provider"] = "Microsoft.Jet.OLEDB.4.0"; ocsb["Data Source"] = "database/SampleDB.MDB"; string connStr = ocsb.ConnectionString; conn = new OleDbConnection(connStr); conn.Open(); string sSQL = "SELECT prodid, prodname, price FROM products"; cmd = new OleDbCommand(sSQL, conn); reader = cmd.ExecuteReader(); while (reader.Read()) { int id = reader.GetInt32(0); string name = reader.GetString(1); decimal price = reader.GetDecimal(2); Console.WriteLine("{0,-5} {1,-30} {2,10:#,0.00}", id, name, price); } reader.Close(); string uSQL = "UPDATE products SET price = price * 1.1"; cmd = new OleDbCommand(uSQL, conn); cmd.ExecuteNonQuery(); string iSQL = "INSERT INTO products VALUES(?, ?, ?)"; cmd = new OleDbCommand(iSQL, conn); p = cmd.Parameters.Add("p1", OleDbType.Integer); p.Value = 5000; q = cmd.Parameters.Add("p2", OleDbType.VarChar); q.Value = "scissors"; cmd.Parameters.Add("p3", OleDbType.Decimal).Value = 18.75; cmd.ExecuteNonQuery(); conn.Close(); } } }

Data Sets, Data Tables, Data Columns, Constraints, Data Relations, Data Rows
/* * * * */ Schema: products(productID, description, price) sales(salesID, productID, quantity) FK productID Ref products DELETE RESTRICT, UPDATE CASCADE

using System; using System.Data; // create a data set... DataSet ds = new DataSet("Sample Data Set"); // create the 'products' table... DataTable dtp = new DataTable("products"); // define the table columns... DataColumn dcp = new DataColumn("productID", typeof(int)); dtp.Columns.Add(dcp); // set the primary key (implied non-null constraint)... Constraint pk = new UniqueConstraint(dcp, true); dtp.Constraints.Add(pk); dtp.Columns.Add("description", typeof(string)); dtp.Columns["description"].AllowDBNull = false; dtp.Columns.Add("price", typeof(decimal)); dtp.Columns[2].AllowDBNull = false; // add the table to the data set... ds.Tables.Add(dtp); // create the 'sales' table... DataTable dts = ds.Tables.Add("sales"); // define the table columns... DataColumn c1 = ds.Tables["sales"].Columns.Add("salesID", typeof(int)); DataColumn c2 = dts.Columns.Add("productID", typeof(int)); // set the (composite) primary key... dts.Constraints.Add( new UniqueConstraint(new DataColumn[] { c1, c2 }, true)); // define and set a foreign key constraint... // can also be established using a DataRelation object... ForeignKeyConstraint fk = new ForeignKeyConstraint(dcp, c2); fk.DeleteRule = Rule.None; // delete restrict... fk.UpdateRule = Rule.Cascade; // update cascade... dts.Constraints.Add(fk); dts.Columns.Add("quantity", typeof(decimal)); // nulls not allowed...

// populate the tables with data... DataRow drp1 = dtp.NewRow(); // new product record... drp1["productID"] = 1001; // set column values for the new record... drp1[1] = "ballpen"; drp1[2] = 12.50; dtp.Rows.Add(drp1); // add record to the table's collection of records... DataRow drp2 = dtp.NewRow(); drp2.ItemArray = new object[] { 1002, "envelope", 8.00 }; dtp.Rows.Add(drp2); dtp.Rows.Add(1003, "stapler", 21.75); DataRow drs = dts.NewRow(); // new sales record... drs[0] = 100; drs[1] = 1001; // this value is checked by the foreign key constraint... drs[2] = 5; dts.Rows.Add(drs); dts.Rows.Add(101, 1002, 2); dts.Rows.Add(102, 1003, 1); // retrieve a row for editing... DataRow rowToEdit = dtp.Rows.Find(1001); // modify the primary key value (which causes a cascade operation)... rowToEdit["productID"] = 2001; // commit changes... ds.AcceptChanges(); can be done for single DataTable or DataRow...

// list all product records... foreach (DataRow row in dtp.Rows) { System.Console.WriteLine("{0} {1} {2}", row[0], row[1], row[2]); } // list all sales records... for (int i = 0; i < dts.Rows.Count; i++) { DataRow row = dts.Rows[i]; System.Console.WriteLine("{0} {1} {2}", row[0], row[1], row[2]); } // delete the last sales record... dts.Rows[dts.Rows.Count - 1].Delete(); // rollback changes... dts.RejectChanges(); can be done also for single DataSet or DataRow...

// uncommenting any of the next two lines will cause an exception to be // thrown due to the delete restrict foreign key constraint... // rowToEdit.Delete(); // dtp.Rows.Remove(rowToEdit);

Data Adapters
using System; using System.Data; using System.Data.OleDb; // create and open a connection to the data source... OleDbConnectionStringBuilder ocsb = new OleDbConnectionStringBuilder(); ocsb["Provider"] = "Microsoft.Jet.OLEDB.4.0"; ocsb["Data Source"] = "SampleDB.MDB"; OleDbConnection conn = new OleDbConnection(ocsb.ConnectionString); conn.Open(); // SQL SELECT query to be used for data retrieval... string sql = "SELECT * FROM products ORDER BY prodid"; // create the data adapter... OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn); // create and register a command builder for RowUpdating events generated // by the data adapter... the builder uses the adapters SelectCommand // to create the InsertCommand, UpdateCommand, and DeleteCommand objects // used to send data changes back to the data source... OleDbCommandBuilder cb = new OleDbCommandBuilder(adapter); // display the DML queries generated by the command builder... System.Console.WriteLine(cb.GetInsertCommand().CommandText); System.Console.WriteLine(cb.GetUpdateCommand().CommandText); System.Console.WriteLine(cb.GetDeleteCommand().CommandText); // create a data set... DataSet ds = new DataSet(); // let the data adapter populate the data set by fetching records from the // data source and storing these in a table named 'products'... adapter.Fill(ds, "products"); // display the retrieved records... DataTable dt = ds.Tables["products"]; foreach (DataRow row in dt.Rows) { System.Console.WriteLine("{0} {1} {2}", row[0], row[1], row[2]); } // make changes to the in-memory copy of the data... dt.Rows[0]["price"] = ((decimal) dt.Rows[0]["price"]) * 1.1m; dt.Rows[1].Delete(); dt.Rows.Add(5000, "dvd-r", 9.50); // send all data changes to the underlying data source... adapter.Update(dt); // commit in-memory data changes... ds.AcceptChanges();

Transaction Processing transaction o logical unit of work in data processing o consists of one or more changes to data which must be executed in an atomic (i.e., all-or-nothing) fashion o commit, rollback, isolation level, nested transactions o NOTE: Transaction processing support may be dependent on the data provider and/or backend data source technology.
using System.Data; using System.Data.OleDb; // set up and open connection to data source... OleDbConnection conn = new OleDbConnection(someConnectionString); conn.Open(); // initiate a new transaction on the connection, and indicate that any // data changes made by this transaction will become available to other // transactions only after those changes have been committed... OleDbTransaction trans = conn.BeginTransaction(IsolationLevel.ReadCommitted); try { // create a command and associate it with the connection/transaction... OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn; cmd.Transaction = trans; // execute the transaction's component commands... cmd.CommandText = "INSERT ..."; cmd.ExecuteNonQuery(); cmd.CommandText = "UPDATE ..."; cmd.ExecuteNonQuery(); cmd.CommandText = "DELETE ..."; cmd.ExecuteNonQuery(); // make these data changes permanent (if possible)... trans.Commit(); } catch { // all the transaction commands cannot be completed for some reason, // so undo any data changes made by this transaction... trans.Rollback(); } // the previous transaction has completed, so the next transaction may // then be initiated here...

Das könnte Ihnen auch gefallen