03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

712 ❘ APPENDIX A Solutions to Exercises<br />

If a program creates a connection at the module level and uses the connection in multiple<br />

methods, each method must be certain that it closes the connection before it exits. You<br />

can use the finally section of a try-catch-finally block to ensure that the connection<br />

is closed.<br />

Alternatively you could use the following code to open the connection.<br />

if (connection.State == ConnectionState.Closed) connection.Open();<br />

6. The InsertThreeRecords example program does this. The following code shows its<br />

InsertInstructorsRecord method.<br />

// Insert an Instructors record.<br />

private void InsertInstructorsRecord(OleDbConnection connection, int<br />

instructorId, string firstName, string lastName, string department)<br />

{<br />

string insert =<br />

"INSERT INTO Instructors (InstructorId, FirstName, LastName, Department)"<br />

+ "VALUES (" + instructorId.ToString() + ", '"<br />

firstName + "', '" + lastName + "', '" + department + "')";<br />

using (OleDbCommand command = new OleDbCommand(insert, connection))<br />

{<br />

// Execute the command.<br />

command.ExecuteNonQuery();<br />

}<br />

}<br />

Download the example to see the other details.<br />

If you omit the UPDATE statement’s WHERE clause, it updates all of the records in the table. In<br />

this example, that means every instructor’s first name is changed to Fran.<br />

7. The AdHocQuery example program does this. The following code shows how the program<br />

displays a row’s values.<br />

// Get the values.<br />

object[] values = new object[reader.FieldCount];<br />

reader.GetValues(values);<br />

// Add the values to a string.<br />

string result = "";<br />

for (int i = 0; i < reader.FieldCount; i++)<br />

{<br />

result += values[i].ToString() + " ";<br />

}<br />

// Display the result.<br />

resultsListBox.Items.Add(result);<br />

Download the example for other details.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!