prof. yousef b. mahdy -2013-2014 distributed database systems prof. yousef b. mahdy mysql-5 updating...

105
Prof. Yousef B. Mahdy -2013-2014 Prof. Yousef B. Mahdy -2013-2014 Distributed Database Systems Prof. Yousef B. Mahdy Prof. Yousef B. Mahdy MySQL-5 Updating Data

Upload: hilary-harvey

Post on 29-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

Issues in ATM Network ControlDistributed Database
Background
ADO.NET is a set of classes that comes with the Microsoft .NET framework to facilitate data access from managed languages. ADO.NET has been in existence for a long time and it provides a comprehensive and complete set of libraries for data access.
The strength of ADO.NET is firstly that it lets applications access various types of data using the same methodology. If I know how to use ADO.NET to access a SQL Server database then the same methodology can be used to access any other type of database (like Oracle or MS Access) by just using a different set of classes.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
1
Secondly, ADO.NET provides two models for data access: a connected model where I can keep the connection with the database and perform data access, and another way is to get all the data in ADO.NET objects that let us perform data access on disconnected objects.
The next diagram shows that ADO.NET can be used with any kind of application, i.e., it can be used from a Windows Forms application, an ASP.NET application, or from a WPF and/or Silverlight application.
Also, the data store underneath can be any data store, SQL Server, Access, or Oracle. It is just a matter of using the right set of classes specific to that data store and the methodology will remain the same.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
2
3
In a typical scenario requiring data access, we need to perform four major tasks:
Connecting to the database
Passing the request to the database, i.e., a command like select, insert, or update.
Getting back the results, i.e., rows and/or the number of rows effected.
Storing the result and displaying it to the user.
This can be visualized as shown in the next slide. So now we need to understand how we can achieve these functionalities using ADO.NET.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
4
Architecture-1
ADO.NET relies on data providers to provide access to the underlying data source. Each data provider exposes a set of objects that you use to manage connections, retrieve data, and update data. The core objects are the following:
Connection
Command
DataReader
DataAdapter
In addition, ADO.NET provides the DataSet object, which provides a disconnected cache of data. The DataSet object does not require a specific type of data source and is not tied to the underlying data source that the data was obtained from.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
1
2
Connection: This object represents a connection to a database.
Command: This object represents an SQL statement that is run while connected to a data source. This object can be a stored procedure or a direct SQL statement.
DataReader: This object retrieves a read-only, forward-only stream of data from a database. The DataReader object is designed for connected scenarios and offers better performance than reading data into a DataSet object at the expense of functionality.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
3
DataAdapter: This object channels data to and from a DataSet object and the underlying data source. The DataAdapter object also provides enhanced batch update features that were previously associated with the ADO Recordset object.
DataSet: The DataSet object represents a disconnected, cached set of data. The DataSet is independent of the provider and is not tied to the underlying data source that might have been used to populate it. DataSet can easily be passed from component to component through the various layers of an application, and it can be serialized as XML.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
4
A DataSet consists of one or more DataTable objects together with DataRelation objects that maintain table relationship information.
Each DataTable contains DataRow objects and DataColumn objects. Constraint objects are used to represent a constraint that can be enforced on one or more DataColumn objects.
DataView. Although the DataView object is not shown in Figure 12.1, you can use a DataView to sort and filter data in a DataTable. This capability is often used for data binding.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
Architecture-2
The next slide shows the basic architecture of the ADO.NET model. As you can see, the entire ADO.NET model sits between the data source and client applications that can be built using Windows Forms, Web Forms, or even console-based applications.
The Connection is the first component that talks to a data source. In ADO.NET, each data provider (OleDb, Sql, Odbc, or Oracle…..) has its own Connection class.
The Connection component is a mediator between a DataAdapter or a Command component. The DataAdapter components create SQL INSERT , SELECT , UPDATE , and DELETE statements that add, read, update, and delete data from a data source, respectively.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
1
2
Not only does a DataAdapter create these SQL statements, it also executes these statements. Basically, a DataAdapter (with the help of Command ) physically updates and reads data from a data source.
You can use the Command components with or without a DataAdapter. You can directly execute commands and read data in a DataReader , which provides a read-only, forward-only fast access to data. This is best when you need to read data in applications that are not data-bound. You can also see from the above figure that all arrows are double-sided arrows except the arrow connecting a DataReader and Command . A double-sided arrow means data transfer is possible on both sides.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
3
A DataReader can only read data, which is why the DataReader has only a one-sided arrow. This shows that you can fill a DataReader from the Command , but you can't send back data from a DataReader to the Command .
A DataAdapter sits between a data source and a DataSet. It provides Fill and Update methods to fill a DataSet from a data source based on the SELECT statement, and the Update method saves a DataSet 's changes to the data source. The DataSet plays a vital role in data-bound Graphical User Interface (GUI) applications to display and manipulate data. Not only does it provide fast data manipulation using Extensible Markup Language (XML) schemas, it also provides multiple views of data that can be bound with multiple Windows Forms and Web Forms data-bound controls.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
4
A DataSet is a collection of DataTable components. A DataTable represents a table in a data source. You can apply a filter or do sorts on a table. You can bind a DataTable to data-bound controls such as a DataGrid , DataList , ListBox , or ComboBox using DataView .
You can also apply sorts and filters on a DataView .
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
Connected Architecture of ADO.NET
The architecture of ADO.net, in which connection must be opened to access the data retrieved from database is called as connected architecture. Connected architecture was built on the classes: connection, command, datareader and transaction.
Connected architecture is when you constantly make trips to the database for any CRUD (Create, Read, Update and Delete) operation you wish to do. This creates more traffic to the database but is normally much faster as you should be doing smaller transactions.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
1
2
3
XxxConnection: Establishes a connection to a specific data source. For example, the SqlConnection class connects to SQL Server data sources.
XxxCommand: Executes a command from a data source. For example, the SqlCommand class can execute stored procedures or SQL statements in a SQL Server data source.
XxxDataReader:Reads a forward-only, read-only stream of data from a data source. For example, the SqlDataReader class can read rows from tables in a SQL Server data source. It is returned by the ExecuteReader method of the XxxCommand class, typically as a result of a SELECT SQL statement.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
Sequence of events
The XxxDataReader class provides forward-only, read-only access to data in a data source. For example, to use a SqlDataReader to read data from a SQL Server database, you would perform the following steps:
Declare a SqlConnection object to connect to the SQL Server database.
Declare a SqlCommand object containing a SQL SELECT statement to query the database.
Declare a SqlDataReader object.
Open the SqlConnection.
Execute the SqlCommand object by using the ExecuteReader method, and assign the results to the SqlDataReader object.
Use the Read method of the SqlDataReader object to iterate forward through the data, and process the rows.
Close the SqlDataReader.
Close the SqlConnection.
Disconnected Architecture in ADO.NET
The architecture of ADO.net in which data retrieved from database can be accessed even when connection to database was closed is called as disconnected architecture. Disconnected architecture of ADO.net was built on classes: connection, dataadapter, commandbuilder and dataset and dataview.
Disconnected architecture is a method of retrieving a record set from the database and storing it giving you the ability to do many CRUD (Create, Read, Update and Delete) operations on the data in memory, then it can be re-synchronized with the database when reconnecting. A method of using disconnected architecture is using a Dataset.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
1
2
3
XxxDataAdapter: Uses the Connection, Command, and DataReader classes implicitly to populate a DataSet and to update the central data source with any changes made to the DataSet. For example, the SqlDataAdapter class can manage the interaction between a DataSet and a SQL Server 7 database.
XxxConnection : Establishes a connection to a specific data source. For example, the SqlConnection class connects to SQL Server data sources.
XxxCommand:
Executes a command from a data source. For example, the SqlCommand class can execute stored procedures or SQL statements in a SQL Server data source.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
4
CommandBuilder : by default dataadapter contains only the select command and it doesn’t contain insert, update and delete commands. To create insert, update and delete commands for the dataadapter, commandbuilder is used. It is used only to create these commands for the dataadapter and has no other purpose.
DataSet : Dataset is used to store the data retrieved from database by dataadapter and make it available for .net application. To fill data in to dataset fill() method of dataadapter is used and has the following syntax.
 Da.Fill(Ds,”TableName”);
5
 When fill method was called, dataadapter will open a connection to database, executes select command, stores the data retrieved by select command in to dataset and immediately closes the connection.
As connection to database was closed, any changes to the data in dataset will not be directly sent to the database and will be made only in the dataset.
To send changes made to data in dataset to the database, Update() method of the dataadapter is used that has the following syntax.
Da.Update(Ds,”Tablename”);
6
When Update method was called, dataadapter will again open the connection to database, executes insert, update and delete commands to send changes in dataset to database and immediately closes the connection.
As connection is opened only when it is required and will be automatically closed when it was not required, this architecture is called disconnected architecture.
A dataset can contain data in multiple tables.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
7
Sequence of events
The following list describes the sequence you follow when working in a disconnected environment:
Open a connection.
Fill the DataSet by using the Fill method of a DataAdapter.
Close the connection.
Process the DataSet. You can sort, filter, summarize, or display the data in Web or Windows controls. The DataSet automatically tracks any changes to the data.
Open a connection. You can reuse the same connection that you used previously.
Update the data source with the changes in the DataSet by using the Update method of a DataAdapter.
Close the connection.
Data Providers
.NET data providers
The .NET data providers are a core component within the ADO.NET architecture that enables communication between a data source and a component, an XML Web service, or an application. A data provider allows you to connect to a data source, retrieve and manipulate data, and update the data source.
Microsoft .NET Framework Data Providers are divided into two categories: bridge providers and native providers. Bridge providers permit you to use data access libraries, such as OLE DB and Open Database Connectivity (ODBC). The bridge provider wraps the underlying data access library. The bridge provider wraps the underlying data access library.
Native providers, such as those for SQL Server and Oracle, typically offer performance improvements due, in part, to the fact that there is less abstraction.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
2
Data Provider contains four classes or components: Connection, Command, DataAdapter, and DataReader. These four classes can be used to perform following functions:
To set a connection between our projects and the data source using the Connection object.
To execute data queries to retrieve, manipulate, and update data using the Command object.
To move the data between the DataSet and the database using the DataAdapter object.
To perform data queries from the database (read - only) using the DataReader object.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
3
The interface definitions for these classes are available in System.Data and the definitions of classes implementing interfaces are available in different namespaces for various data providers as shown below:
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
4
Since the different class definitions in namespaces of the different DataProviders implement common interfaces, the methods provided by various providers in the following classes are the same.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
5
You can see, only prefix distinguishes the implementations. Likewise, the other classes also are implemented as shown below:
the Command (SqlCommand, OleDbCommand, OdbcCommand, OracleCommand)
the DataReader (SqlDataReader, OleDbDataReader, OdbcDataReader, OracleDataReader)
DataAdapter (SqlDataAdapter, OleDbDataAdapter, OdbcDataAdapter, OracleDataAdapter).
6
Data access with ADO.NET can be summarized as follows:
A connection object establishes the connection for the application with the database. The command object provides direct execution of the command to the database. If the command returns more than a single value, the command object returns a DataReader to provide the data. Alternatively, the DataAdapter can be used to fill the Dataset object. The database can be updated using the command object or the DataAdapter.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
MySql- Downloading Connector/Net
First make sure you have downloaded and installed the MySQL Connector/NET from the MySQL official website.
Adding Reference and Creating the MySQL Connector DLL from the Project:
Before we start writing the code, we need to add the mysql Reference in our project. To do so, we right click our project name, and choose Add Reference:
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
1
2
3
In order to use the application on other computers that don't have the connector installed, we will have to create a DLL from the reference. To do so, we right click the reference name in our project, and set the copy local to true in its properties:
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
3
The Connection
The ADO.NET Connection class is used to establish a connection to the database. The Connection class uses a ConnectionString to identify the database server location, authentication parameters, and other information to connect to the database.
The MySqlConnection class is defined in the MySql.Data.MySqlClient namespace. Before using this class, you can first include this namespace in your file.
Before any type of data access can be made, the most important step is to make a connection to the database. Given the various .NET providers, it is important to use the correct and appropriate "language of connection" which is really the correct construction of what is called the "ConnectionString".
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
1
Simply stated, the ConnectionString consists of a set of database related information separated by semi-colons. This string describes briefly, on which database Server the Database is located, the name of the database queried, and whether or not correct authentication and permissions to view objects are in place, besides a few other details.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
3
Initial Catalog(database):The name of the database.
Data Source(localhost): The name of the Server to be used when a connection is open, or the filename of a Microsoft Access database.
Password: The login password for the SQL Server account.
User ID: The SQL Server login account.
Example: For Mysql:
Opening a Connection
After programmatically creating a connection string, to apply it and actually establish the connection, you must call the MySqlConnection.Open() method. Its syntax is:
Here is an example of calling it:
void InitializeComponent() {
MySqlConnection conn = new MySqlConnection(cs);
1
As you can see, this method does not take any argument. The MySqlConnection object that calls it is responsible to get the connection string ready:
If the connection fails, the compiler would throw a MySqlException exception.
After using a connection and getting the necessary information from it, you should terminate it using the close() method.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
Testing
If the following program runs OK, then we have everything installed OK. We check the version of the MySQL server.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
1
2
Getting the State of a Connection Object
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
Commanding a Database
After establishing a connection, if you are successful, the database system becomes available to you and you can take actions, such as creating a database and/or manipulating data.
An action you perform on the database server or on a database is carried by a object called a command.
To support the various actions that you can perform on a MySQL server database, the MySQL Connector/Net provides the MySqlCommand class. To use it, you can declare a variable of type MySqlCommand using one of its constructors
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
1
2
The Command Object in ADO.NET executes SQL statements and Stored Procedures against the data source specified in the Connection Object.
The Command Object required an instance of a Connection Object for executing the SQL statements. That is, for retrieving data or execute an SQL statement against a Data Source , you have to create a Connection Object and open a connection to the Data Source, and assign the open connection to the connection property of the Command Object.
When the Command Object return result set , a Data Reader is used to retrieve the result set.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
3
The Command Object has a property called CommandText, which contains a String value that represents the command that will be executed in the Data Source. When the CommandType property is set to StoredProcedure, the CommandText property should be set to the name of the stored procedure.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
Command Types
Commands are powerful entities that are capable of complex database manipulation. According to ADO.NET, there are only three types of commands:
Text: A text command is made up of instructions to a managed provider to do some work at the database level.
Stored Procedure: A stored procedure is a command that calls a procedure located within the database itself. The SQL Server, OLE DB, Oracle, and ODBC Managed Providers all support this type of command.
TableDirect: A TableDirect command is a special command type that returns a complete table from the database. This is identical to calling a command of type text with SELECT * FROM TABLENAME.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
1
These three command types cover the entire spectrum of commands you can send to the database. By default, the CommandType is set to a text command. To set the command type, you will use the CommandType enumeration that resides within the System.Data namespace.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
SqlCommand METHODS
Executing Commands
After you have everything in place, you want to execute the command. You can execute ADO.NET commands in a number of ways; the results differ only in how data is returned from the database. The following execution methods are supported by all managed providers:
ExecuteNonQuery(): Calling this method executes the query and returns the number of rows the command affected. This is used to execute commands for which you do not care what the results are. Because the call returns the number of rows affected, ExecuteNonQuery()can be used to determine success in many instances.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
1
ExecuteScalar(): This method executes the command and returns the first column of the first row of the first result set. This is useful for retrieving analysis information from the database (for example, SELECT COUNT(userid) FROM USERS;).
ExecuteReader(): This method executes the command and returns a DataReader object. DataReaders are forward-only streams of records from a database. DataReader objects are discussed in detail in the next chapter. Each of the managed providers' versions of ExecuteReader returns a DataReader object from its namespace (OleDbDataReader, SqlData Reader or OdbcDataReader.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
SqlCommand PROPERTIES
The DataReader
What if you want to execute a query that returns a result set? The Command object has an ExecuteReader method that returns a DataReader object that you can use to examine the results of your query.
The DataReader object is similar to other reader objects in the .NET Framework, such as the XmlReader, TextReader, and StreamReader objects. Each of these objects is an efficient, lightweight object that lets you examine (in a read-only fashion) the data that the object exposes.
Developers who've worked with RDO and ADO or the lower-level ODBC and OLE DB API might be familiar with the term firehose cursor. This is the mechanism that databases use to return the results of a query as quickly as possible. Firehose cursors forgo functionality in favor of performance. Once you've read one row from the result set and moved on to the next row, the previous row is no longer available.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
DataReader
There are two ways to read and store data: one is DataSet and the other is DataReader.
A data reader provides an easy way for the programmer to read data from a database as if it were coming from a stream. The DataReader is the solution for forward streaming data through ADO.NET. The data reader is also called a firehose cursor or forward read-only cursor because it moves forward through the data.
The data reader not only allows you to move forward through each record of database, but it also enables you to parse the data from each column. The DataReader class represents a data reader in ADO.NET.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
1
Similar to other ADO.NET objects, each data provider has a data reader class for example; OleDbDataReader is the data reader class for OleDb data providers. Similarly, SqlDataReader and ODBC DataReader are data reader classes for Sql and ODBC data providers, respectively.
The IDataReader interface defines the functionally of a data reader and works as the base class for all data provider-specific data reader classes such as OleDataReader. SqlDataReader, MySQLDataReader ,and OdbcDataReader.
DataReader objects can be used to read rows only in a forward direction. You cannot use a DataReader to modify rows in the database.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
Initializing DataReader
You call the ExecuteReader method of the Command object, which returns an instance of the DataReader. For example, use the following line of code:
MySqlCommand cmd = new MySqlCommand (SQL, conn);
// Call ExecuteReader to return a DataReader
MySqlDataReader reader = cmd.ExecuteReader();
Once you're done with the data reader, call the Close method to close a data reader:
reader.Close();
The DataReader properties
FieldCount
IsClosed
Item
RecordsAffected
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
The DataReader methods
NextResult
Advances the data reader to the next result during batch transactions.
Getxxx
There are dozens of Getxxx methods. These methods read a specific data type value from a column. For example. GetChar will return a column value as a character and GetString as a string.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
1
Once the MySqlDataReader is initialize, you can utilize its various methods to read your data records. Foremost, you can use the Read method, which, when called repeatedly, continues to read each row of data into the DataRader object.
The DataReader also provides a simple indexer that enables you to pull each column of data from the row.
string str = reader["CustomerID"].ToString(); //Name
string str = reader.GetString(0); //Orinal number
With the GetString method of the CustomerID, you don't need to do any conversion, but you do have known the zero-based column number of the CustomerID (Which, in this case, is zero).
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
Read Method
The Read method accesses the next row of data. Remember that the first row in the result set will not be available through the DataReader until you call the Read method. The first time you call the Read method, the DataReader will move to the first row in the result set. Subsequent calls to Read will move to the next row of data.
The Read method also returns a Boolean value to indicate whether there are any more results for the query. The sample code we examined earlier continually examines results until the Read method returns False.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
9
NextResult Method:
If you're working with batch queries that return multiple result sets, use the NextResult method to move to the next set of results. Like the Read method, NextResult returns a Boolean value to indicate whether there are more results.
Close Method:
When you're using DataReader objects, it's important that you loop through the results and close the DataReader as quickly as possible.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
10
GetName, GetOrdinal, and GetDataTypeName Methods:
The DataReader has methods that you can use to learn more about the results returned by your query. If you want to determine the name of a particular column, you can call the GetName method. If you already know the column name you want to access but don't know its ordinal position within the result set, you can pass the column name into the GetOrdinal method to retrieve its ordinal position. The GetDataTypeName method accepts an integer denoting the ordinal position of the column and returns the data type for that column as a string.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
11
GetSchemaTable Method:
The DataReader object's GetSchemaTable method is similar to the DataAdapter object's FillSchema method. Each method lets you create a DataTable containing DataColumn objects that correspond to the columns returned by your query. The GetSchemaTable method accepts no parameters and returns a new DataTable. The DataTable contains a DataColumn for each column returned by your query, but the Rows collection of the DataTable is empty. GetSchemaTable populates the new DataTable with schema information only.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
Example
1
2
We get all authors from the Books table and print them to the console.
reader = cmd.ExecuteReader();
To create a MySQLDataReader, we must call the ExecuteReader() method of the MySqlCommand object.
while (reader.Read()){
Console.WriteLine(reader.GetInt32(0) + ": " + reader.GetString(1));}
The Read() method advances the data reader to the next record. It returns true if there are more rows; otherwise false. We can retrieve the value using the array index notation, or use a specific method to access column values in their native data types. The latter is more efficient.
 if (rdr != null) {rdr.Close();}
Example- Column headers
1
Dealing with Null Columns
When walking through the records of DataReader, if you try to retrieve a value from a null field, ADO.NET will throw an exception. This exception is caused when attempting to convert the null field to the requested type.
To avoid throwing the exception, the DataReader supports calling the IsDBNull() method, which informs the caller as to whether the field is null.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
Datareader
To execute a Select statement, we add a few more steps, and we use the ExecuteReader method that will return a dataReader object to read and store the data or records.
Open connection to the database.
Create a MySQL command.
Assign a connection and a query to the command. This can be done using the constructor, or using the Connection and the CommandText methods in the MySqlCommand class.
Create a MySqlDataReader object to read the selected records/data.
Execute the command.
Read the records and display them or store them in a list.
Close the data reader.
1
ExecuteNonQuery
The ExecuteNonQuery() is one of the most frequently used method in SqlCommand Object, and is used for executing statements that do not return result sets (ie. statements like insert data , update data etc.) .
Command.ExecuteNonQuery();
The ExecuteNonQuery() performs Data Definition tasks as well as Data Manipulation tasks also. The Data Definition tasks like creating Stored Procedures ,Views etc. perform by the ExecuteNonQuery() .
Also Data Manipulation tasks like Insert , Update , Delete etc. also perform by the ExecuteNonQuery().
ExecuteNonQuery executes the command and returns the number of rows affected.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
ExecuteScalar
Executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored.
Returns: The first column of the first row in the result set, or a null reference if the result set is empty.
Use the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the ExecuteReader method, and then performing the operations necessary to generate the single value using the data returned by a MySqlDataReader
A typical ExecuteScalar query can be formatted as in the following C# example:
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
Working with DML (Insert, Update, Select, Delete)
Usually, Insert, update and delete are used to write or change data in the database, while Select is used to read data. For this reason, we have different types of methods to execute those queries.
The methods are the following:
ExecuteNonQuery: Used to execute a command that will not return any data, for example Insert, update or delete.
ExecuteReader: Used to execute a command that will return 0 or more records, for example Select.
ExecuteScalar: Used to execute a command that will return only 1 value, for example Select Count(*).
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
1
I will start with Insert, update and delete, which are the easiest. The process to successfully execute a command is as follows:
Open connection to the database.
Create a MySQL command.
Assign a connection and a query to the command. This can be done using the constructor, or using the Connection and the CommandText methods in the MySqlCommand class.
Execute the command.
Close the connection.
2
3
4
5
6
7
8
9
Fetching Multiple Results
dotConnect for MySQL supports execution of batch SQL statements separated by ';' separator. For example, you can execute following SQL:
select * from emp; select * from dept
if you write next code:
MySqlCommand Mycmd;
MySqlDataReader reader;
1
The DataReader exposes a NextResult method that lets you move to the results of the next row-returning query. The NextResult method is similar to the Read method in that it returns a Boolean value to indicate whether there are more results. However, unlike with the Read method, you should not call this method initially.
As a result of the execution you get open data reader positioned on the first result of the query. Call MySqlDataReader.NextResult method to advance to the next result. If you set MySqlCommand.FetchAll property to true you can reach any result using MySqlDataReader.CurrentResult and MySqlDataReader.ResultCount properties.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
2
You can use multiple results queries to specify MySqlDataAdapter.InsertCommand .
NextResult Method is used to process multiple results, which can be generated by executing batch SQL statements. By default, the MySqlDataReader is positioned on the first result.
You can determine what result is current using CurrentResult property. Total amount of results stored in MySqlDataReader is represented by ResultCount property.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
Example-1
Executing a Query That Returns a Single Value
What if you want to execute a query and retrieve a single cell (one row, one column) of data? Here are two examples of queries that return a single value:
SELECT COUNT(*) FROM Customers
SELECT CompanyName FROM Customers WHERE CustomerID = 'ALFKI'
Using a DataReader or a DataSet to retrieve this single value is probably overkill. The Command object has a method specifically designed for such queries: ExecuteScalar. This method returns the value through the generic object data type, which you can then convert to the desired data type, as shown here:
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
1
The ExecuteScalar method is a great example of a feature that offers a better solution to a coding scenario that you might not have even realized was fairly inefficient.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
Prepared statements
Now we will concern ourselves with prepared statements. When we write prepared statements, we use placeholders instead of directly writing the values into the statements. Prepared statements increase security and performance.
In this case we use a parameterized command. Consider the following query:
SELECT FirstName FROM persons WHERE ID = 2
This query can be rewritten by using parameters as follows:
SELECT FirstName FROM persons WHERE ID = @ID
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
1
The @ID is a placeholder, which is going to be filled later.
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
2
cmd.CommandText = "select productname from products where ProductID=@ID";
cmd.Prepare();
Here we create a prepared statement. When we write prepared statements, we use placeholders instead of directly writing the values into the statements. Prepared statements are faster and guard against SQL injection attacks. The @ID is a placeholder, which is going to be filled later.
The parameter is adding as follows:
cmd.Parameters.AddWithValue("@ID", 12);
1-* - Prof Yousef B. Mahdy- * Distributed Database Management Systems
3
string FName= cmd.ExecuteScalar().ToString ();
The ExecuteScalar method is used when the query return one Value.
The prepared statement is executed.
SQL Server 7.0
n
server until the connection
n
the server while the data is
processed
1.