Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Лаба №1 / books / csharp_ebook.pdf
Скачиваний:
77
Добавлен:
03.03.2016
Размер:
3.69 Mб
Скачать

Programmers Heaven: C# School

Updating the table

So far we have only selected the data from the database and haven't changed any row, inserted new rows or deleted existing rows. Let's learn how to perform these tasks one by one.

Please note that for this section, we will only use the "Article" table and will not be using the "Author" table, for the sake of simplicity.

Updating a table in ADO.Net is very interesting and easy. You need to follow these steps to update, insert and delete records:

The Data Adapter class (SqlDataAdapter) has properties for each of the insert, update and delete commands. First of all we need to prepare the command (SqlCommand) and add it to the data adapter object. The commands are simple SQL commands with parameters. To implement this step, we will introduce a method InitializeCommands() in the following example.

Secondly we need to add parameters to these commands. The parameters are simply the names of the data table fields involved in the particular command. To implement this step, we will introduce a method named AddParams() in the following example.

The two steps described above are done only once in the application. For each insert, update and delete; we insert, update and delete the corresponding data row (DataRow) of the data table (DataTable) object.

242

Programmers Heaven: C# School

After any update we call the Update() method of the data adapter class by supplying to it, the dataset and table name as parameters. This updates our local dataset.

Finally we call the AcceptChanges() method of the dataset object to store the changes in the dataset to the physical database.

Again for simplicity we haven't included the steps for data validation, which is a key part of a data update in a real application.

Building the Application

The application will finally look like this:

In this application, we have defined several data access objects (like SqlDataAdapter, DataSet) as private class members so that we can access them in different methods.

public class ADOForm : System.Windows.Forms.Form

{

// Private global members to be used in various methods

private SqlConnection conn;

private SqlDataAdapter dataAdapter;

243

Programmers Heaven: C# School

private DataTable dataTable; private DataSet ds;

private int currRec=0; private int totalRec=0; private bool insertSelected;

...

Loading the table and displaying data in the form's controls

The event handler for the 'Load Table' button has changed a bit and now looks like this:

private void btnLoadTable_Click(object sender, System.EventArgs e)

{

this.Cursor = Cursors.WaitCursor;

string connectionString ="server=P-III; database=programmersheaven;uid=sa; pwd=;";

conn = new SqlConnection(connectionString); string commandString = "SELECT * from article";

dataAdapter = new SqlDataAdapter(commandString, conn); ds = new DataSet();

dataAdapter.Fill(ds, "article");

dataTable = ds.Tables["article"]; currRec = 0;

totalRec = dataTable.Rows.Count;

FillControls();

//

show current record on the form

InitializeCommands();

//

prepare commands

ToggleControls(true);

// enable corresponding controls

this.Cursor = Cursors.Default;

}

We have changed the cursor to WaitCursor at the start of the method, and changed it to Default at the end of the method. Later we have called the InitializeCommands() method after filling the controls with the first record.

Initialing Commands

The InitializeCommands() is the key method to understand in this application. It is defined in the program as:

private void InitializeCommands()

{

244

Programmers Heaven: C# School

//Preparing Insert SQL Command dataAdapter.InsertCommand = conn.CreateCommand(); dataAdapter.InsertCommand.CommandText =

"INSERT INTO article " +

"(artId, title, topic, authorId, lines, dateOfPublishing) " + "VALUES(@artId, @title, @topic, @authorId, @lines, @dateOfPublishing)"; AddParams(dataAdapter.InsertCommand, "artId", "title", "topic", "authorId", "lines", "dateOfPublishing");

//Preparing Update SQL Command

dataAdapter.UpdateCommand = conn.CreateCommand(); dataAdapter.UpdateCommand.CommandText =

"UPDATE article SET " +

"title = @title, topic = @topic, authorId = @authorId, " + "lines = @lines, dateOfPublishing = @dateOfPublishing " + "WHERE artId = @artId";

AddParams(dataAdapter.UpdateCommand, "artId", "title", "topic", "authorId", "lines", "dateOfPublishing");

// Preparing Delete SQL Command dataAdapter.DeleteCommand = conn.CreateCommand();

dataAdapter.DeleteCommand.CommandText = "DELETE FROM article WHERE artId = @artId"; AddParams(dataAdapter.DeleteCommand, "artId");

}

The SqlDataAdapter (and OleDbDataAdapter) class has properties for each of the Insert, Update and Delete commands. The type of these properties is SqlCommand (and OleDbCommand respectively). We have created the Commands using the connection (SqlConnection) object's CreateCommand() method.

We then set the CommandText property of these commands to the respective SQL queries in string format. The thing to note here is that the above commands are very general and we have used the name of the fields with an '@' sign wherever the specific field value is required. For example, we have written the DeleteCommand's CommandText as:

"DELETE FROM article WHERE artId = @artId";

Here we have used @artId instead of any physical value. In fact, this value would be replaced by the specific value when we delete a particular record.

245

Соседние файлы в папке books