ADO.NET Access Data Object
ADO.NET Conjunto de classes que permitem o acesso à base de dados. Dois cenários: Connected Os dados provenientes da base de dados são obtidos a partir de uma ligação que se mantém aberta enquanto percorremos os valores Disconnected Os dados são transferidos da base de dados para memória e após o carregamento a conexão é fechada automaticamente Namespace System.Data 1
.Net Data Providers Providers: SQL Server - System.Data.SqlClient OLE DB - System.Data.OleDb ODBC - System.Data.Odbc Oracle - System.Data.OracleClient. Object: Connection Command DataReader DataAdapter provides connectivity to a data source enables access to database commands to return data, modify data, run stored procedures, and send or retrieve parameter information provides a high-performance stream of data from the data source read-only, forward-only provides the bridge between the DataSet object and the data source. Uses Command objects to execute SQL commands 2
The DataSet object is central to supporting disconnected, distributed data scenarios with ADO.NET. The DataSet is a memory-resident representation of data that provides a consistent relational programming model regardless of the data source The DataSet represents a complete set of data, including related tables, constraints, and relationships among the tables. 3
Arquitectura ADO.NET Relationship between a.net Framework data provider and a DataSet 4
Acesso a Bases de Dados 5
Acesso a Bases de Dados Connected 1. Create a connection SqlConnection, OleDbconnection, 2. Create a command SqlCommand, Oledbcommand, 3. Execute Command 4. Use DataReader 6
Objecto Connection SqlConnection / OleDbConnection string strconn = "data source=localhost; " + "initial catalog=northwind; " + "integrated security=true"; SqlConnection conn = new SqlConnection(); conn.connectionstring=strconn; ConnectionString parameters: Connection timeout Password Data source Persist security info Initial catalog User ID Integrated security Provider Examples: http://www.connectionstrings.com/ 7
Objecto Command SqlCommand / OleDbCommand Represents an SQL statement or stored procedure to execute against a data source. SqlCommand com = new SqlCommand(); com.connection = conn; com.commandtext="select * From Tabela;"; SqlDataReader Info = com.executereader(); Properties: Connection Command Text - Query SQL Parameters 8
Objecto Command Execute SQL commands ExecuteReader Executes commands that return rows - queries. (SELECT) ExecuteNonQuery Executes commands such as SQL INSERT, DELETE, UPDATE, and SET statements. ExecuteScalar Retrieves a single value, for example, an aggregate value from a database (Ex: Count) 9
Data Command private System.Data.OleDb.OleDbConnection myconnection; private System.Data.OleDb.OleDbCommand cmd; String connstr="provider=microsoft.jet.oledb.4.0; Data Source=" + strpath; String strsql="insert into Produtos (IdCat,NomeProd,Preco) Values ('1','" + nomeprod + "'," + "'" + preco +"')" ; myconnection=new System.Data.OleDb.OleDbConnection(connstr); myconnection.open(); cmd=new OleDbCommand (strsql,myconnection); (*) cmd.executenonquery(); myconnection.close(); (*) cmd=new OleDbCommand(); cmd.connection=myconnection; cmd.commandtext=strsql; Constructor or Property 10
Data Command Use parameters in SQL String strsql = "Insert into Produtos (IdCat, NomeProd, Preco) Values (?,?,?)"; myconnection = new OleDbConnection(myConnectionstr); cmd = new System.Data.OleDb.OleDbCommand( ); cmd.connection = myconnection; Parameters cmd.commandtext = strsql; cmd.parameters.addwithvalue("idcat",idcat); cmd.parameters.addwithvalue("nomeprod",nomeprod); cmd.parameters.addwithvalue("preco",preco);? - MS Access @ - MS SQL Server : - Oracle). 11
Date Parameter OleDbCommand cmd = conn.createcommand(); cmd.commandtext = "INSERT INTO facturas (clienteid, datacriacao) VALUES (?,?)"; cmd.parameters.add("cid", 347); OleDbParameter parm = cmd.parameters.add("dt", OleDbType.Date); parm.value= DateTime.Now; cmd.executenonquery(); 12
Objecto DataReader SqlDataReader / OleDbDataReader Provides a way of reading a forward-only stream of data rows from a data source. This class cannot be inherited. To create an OleDbDataReader call the ExecuteReader method of the OleDbCommand object SqlDataReader Info = com.executereader(); DataGrid1.DataSource=Info; forward-only and read-only Properties FieldCount HasRows IsClosed Close GetString GetInt32 13
Objecto DataReader DataSource de Server Controls string sql ="SELECT Nome FROM Categorias"; OleDbConnection conn = new OleDbConnection(connstr); OleDbCommand cmd = new OleDbCommand(sql,conn); conn.open(); OleDbDataReader myreader; myreader = mycommand.executereader(); gridviewobj.datasource=myreader; gridviewobj.databind(); 14
Objecto DataReader Métodos: Read lê um registo do resultado do Query, permite iterar sobre o objecto GetFloat, GetInt, GetString, etc permite aceder aos campos do registo GetSchemaTable Devolve um Data Table com a informação do Schema do resultado do Query while (dtreader.read()) { HyperLink hlink=new HyperLink(); hlink.text=dtreader.getstring(1); // (string)dtreader[ NomeCat ]; hlink.navigateurl="http://localhost/produtos.aspx?prod= "+dtreader.getint32(0); Panel1.Controls.Add(hlink); Panel1.Controls.Add(new LiteralControl("<P/>")); } 15
Data-Bound Web Server Controls ASP.NET Data-Bound Web Server Controls GridView displays data as a table and provides the capability to sort columns, page through data, and edit or delete a single record DetailsView renders a single record at a time as a table and provides the capability to page through multiple records, as well as to insert, update, and delete records. FormView renders a single record at a time from a data source and provides the capability to page through multiple records, as well as to insert, update, and delete records. FormView control does not specify a built-in layout. 16
Data-Bound Web Server Controls Repeater renders a read-only list from a set of records returned from a data source. Repeater control does not specify a built-in layout. DataList renders data as table and enables you to display data records in different layouts, such as ordering them in columns or rows ASP.NET Data-Bound Web Server Controls Overview https://msdn2.microsoft.com/en-us/library/ms228214.aspx 17