Retrieving Data from the Database

Một phần của tài liệu Beginning Databases with Postgre SQL phần 9 pot (Trang 21 - 28)

To retrieve data from the database, we need to use two additional Npgsql classes:

the NpgsqlCommand class and the NpgsqlDataReader class. We will start by looking at the NpgsqlCommand class, which allows us to send commands, such as a SELECT statement, to the database.

Sending Commands with NpgsqlCommand

The NpgsqlCommand class has a number of constructors. The most commonly used form is to pass the text of the command required and a connection object, as follows:

NpgsqlCommand(string SQLCommand, NpgsqlConnection connectionobject);

Here, the string parameter is a valid SQL statement, such as "SELECT fname, lname FROM customer", and the NpgsqlConnection is a connection object as before, which provides information about the connection to the PostgreSQL database.

Once instantiated, there are several properties that we can retrieve or update for our NpgsqlCommand object. The most commonly used properties are listed in Table 18-4.

Here is how we might create our command object to retrieve information from the customer table:

NpgsqlCommand cmd =

new NpgsqlCommand("SELECT * FROM customer", conn);

If we subsequently wanted to change the SQL statement, we just update the CommandText property, like this:

cmd.CommandText = "SELECT * from orderinfo";

Once we have a command object, we can use its methods to perform actions against the database. The main methods are shown in Table 18-5.

Table 18-4. Common NpgsqlCommand Properties

Method Meaning

CommandText Allows the command text to be retrieved or set

CommandTimeout Sets how long the system will wait for the command to execute before terminating it

CommandType Sets or gets the type of command; by default, this is Text for executing SQL statements, but can also be Stored Procedure when the command is to execute a stored procedure

Connection Sets or gets the connection object to be used Parameters Allows access to parameters for prepared statements

Transaction Sets or gets the transaction in which the command is to execute

Table 18-5. Common NpgsqlCommand Methods

Method Meaning

Dispose Releases all the resources in use

ExecuteNonQuery Executes a SQL statement that doesn’t retrieve data ExecuteReader Executes a SQL statement that will return data; returns an

NpgsqlDataReader object

Prepare Makes a prepared statement ready for execution

The method we are most interested in is ExecuteReader, which returns an NpgsqlDataReader object. Here is an example:

NpgsqlDataReader datard = cmd.ExecuteReader();

The NpgsqlDataReader object is the next class we need to look at in the Npgsql assembly.

Getting Data with the NpgsqlDataReader Class

The NpgsqlDataReader class is the one that actually allows us to get at the data (and meta data) when we retrieve data from the database. It’s normally created by the execution of an ExecuteReader method on the NpgsqlCommand object. Since it has quite a bit of work to do, it’s the most complex object we have yet encountered in the Npgsql assembly, but it’s not hard to use. This class’s most commonly used properties are listed in Table 18-6.

The Item property is quite clever. You simply use the name of the data reader object with an array accessor [], using either an index of the column offset or passing a string containing the name of the column. In either case, the data contents of the column are returned in its native format. We will see both of these types of array access in the next two code examples.

This means that if we create an NpgsqlDataReader object datard, then once it is populated, we can access the value of the third column by writing datard[3], which leads to client code that is much easier to read. If we prefer, we can also access the data using the column name, by passing in a string as the array index: datard["lname"].

The data reader object also has quite a long list of methods. Table 18-7 lists the most commonly used methods.

Table 18-6. Common NpgsqlDataReader Properties

Property Meaning

FieldCount Provides the number of columns in the data row

HasRows Set to true if there is one or more rows of data ready to be read IsClosed Set to true if the data reader has been closed

Item Retrieves the column in its native format

RecordsAffected Provides the number of rows affected by the SQL statement

Table 18-7. Common NpgsqlDataReader Methods

Method Meaning

Close Closes the data reader object Dispose Releases all the resources in use GetBoolean Gets a column value as a Boolean value GetDateTime Gets a column value as a datetime value

Remember that the easiest way to access the data value is via an array reference, using the Item property.

Retrieving data from the database is not difficult. In practice, you will often need only a small subset of the properties and methods available. Our next program, getdata1.cs, shows the basic properties and methods we need to retrieve some data. The key changes from our earlier program are highlighted.

// Getdata1.cs - a simple retrieve of data from the customer table using System;

using Npgsql;

public class connect {

public static void Main(String[] args) { NpgsqlConnection conn = new

NpgsqlConnection("Server=192.168.0.3;Port=5432;

User Id=rick;Password=password;Database=bpfinal;");

try {

conn.Open();

NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM customer", conn);

NpgsqlDataReader datard = cmd.ExecuteReader();

while (datard.Read()) {

for (int i=0; i<datard.FieldCount; i++) { Console.Write("{0}, ", datard[i]);

}

GetDecimal Gets a column value as a decimal number GetDouble Gets a column value as a double

GetFieldType Returns the data type of the column at an index position GetFloat Gets a column value as a floating-point number GetInt16 Gets a column value as a 16-bit integer

GetInt32 Gets a column value as a 32-bit integer GetInt64 Gets a column value as a 64-bit integer GetName Gets the column name of a column by index GetString Gets a column value as a string

IsDBNull True if the value in a column is NULL Read Advances the data reader to the next row Table 18-7. Common NpgsqlDataReader Methods (Continued)

Method Meaning

Console.WriteLine();

} }

finally { conn.Close();

} } }

When we run this in MonoDevelop, a console window opens and displays the retrieved data, as shown in the example in Figure 18-2.

Figure 18-2. C# code in MonoDevelop retrieving data

The key changes are that we created a new NpgsqlCommand object, passing it a SQL statement to retrieve all the data from the customer table, as well as the NpgsqlConnection object we previ- ously opened. We then call the ExecuteReader method, which returns a new NpgsqlDataReader object. By repeatedly calling the Read method, we iterate through the retrieved rows. We use the FieldCount property to determine how many columns there are in the row. Notice we access the data by using an index of the column number directly into the data reader object:

datard[i]. This retrieves the actual data value, which we print to the console.

Retrieving Meta Data

It’s often very useful to be able to retrieve meta data, or data about the data, from a database.

We can do this quite easily using the methods we have already seen. The following program, Getdata2.cs, builds on Getdata1.cs, adding code to retrieve the names and types of the columns being retrieved. The changed lines are highlighted.

// getdata2.cs - a simple retrieve of meta data from the customer table using System;

using Npgsql;

public class connect {

public static void Main(String[] args) { NpgsqlConnection conn = new NpgsqlConnection(

"Server=192.168.0.3;User Id=rick;Password=password;Database=bpfinal;");

try {

conn.Open();

NpgsqlCommand cmd =

new NpgsqlCommand("SELECT * FROM customer", conn);

NpgsqlDataReader datard = cmd.ExecuteReader();

datard.Read();

Console.Write("There are {0} columns\n", datard.FieldCount);

for (int i = 0; i < datard.FieldCount; i++) { Console.Write("Name: {0}, NpgsqlType: {1}", datard.GetName(i), datard.GetFieldType(i));

Console.WriteLine();

}

Console.Write("First row by named column: {0}, {1}", datard["fname"], datard["lname"]);

}

finally { conn.Close();

} } }

We use the GetName and GetFieldType methods of the data reader to retrieve the name and column types. We also use a field name, rather than the column index as in the previous example, to retrieve data.

Using Npgsql Event Logging

Before we move on, we will take a brief look at the event logging capabilities of Npgsql. We can debug programs using Npgsql in the same way that we debug any C# program: by adding

statements to print out data or by stepping through the program in a debugger. However, for some types of error tracking, what we would like is an easy-to-use method of tracing what Npgsql is doing. The Npgsql assembly has a special event log for doing just that. It is very simple to use, with only the three properties listed in Table 18-8.

We can see this in action in a simple demonstration program, Debug.cs.

// Debug.cs using System;

using Npgsql;

public class connect {

public static void Main(String[] args) { NpgsqlEventLog.Level = LogLevel.Debug;

NpgsqlEventLog.LogName = "/tmp/Npgsqldebug.txt";

NpgsqlEventLog.EchoMessages = true;

NpgsqlConnection conn = new NpgsqlConnection(

"Server=192.168.0.3;User Id=rick;Password=password;Database=bpfinal;");

try {

conn.Open();

NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM customer", conn);

NpgsqlDataReader datard = cmd.ExecuteReader();

datard.Read();

Console.Write("{0}, {1}, {2}", datard[0], datard[1], datard[2]);

Console.WriteLine();

}

finally { conn.Close();

} } }

Table 18-8. NpgsqlEventLog Properties

Property Meaning

EchoMessages Sets if message should be printed to the console: true or false Level Sets the level of messages required: None, Normal, or Debug Logname Sets the name of the file to write to, if required

When we run this program, a console window immediately opens, showing the logging text, as in the example in Figure 18-3.

Figure 18-3. Log tracing in progress

The textual log file written is very similar, with the addition of timestamp information.

Một phần của tài liệu Beginning Databases with Postgre SQL phần 9 pot (Trang 21 - 28)

Tải bản đầy đủ (PDF)

(66 trang)