SACommand: Fetch Data Using ExecuteReader and ExecuteScalar

The SACommand object allows you to execute a SQL statement or call a stored procedure against an SAP Sybase IQ database. You can use any of the following methods to retrieve data from the database:

When using the SACommand object, you can use the SADataReader to retrieve a result set that is based on a join. However, you can only make changes (inserts, updates, or deletes) to data that is from a single table. You cannot update result sets that are based on joins.

When using the SADataReader, there are several Get methods available that you can use to return the results in the specified data type.

C# ExecuteReader Example

The following C# code opens a connection to the SAP Sybase IQ sample database and uses the ExecuteReader method to create a result set containing the last names of employees in the Employees table:

SAConnection conn = new SAConnection("Data Source=Sybase IQ Demo");
conn.Open();
SACommand cmd = new SACommand("SELECT Surname FROM Employees", conn);
SADataReader reader = cmd.ExecuteReader();
listEmployees.BeginUpdate();
while (reader.Read())
{
    listEmployees.Items.Add(reader.GetString(0));
}
listEmployees.EndUpdate();
reader.Close();
conn.Close();

Visual Basic ExecuteReader Example

The following Visual Basic code opens a connection to the SAP Sybase IQ sample database and uses the ExecuteReader method to create a result set containing the last names of employees in the Employees table:

Dim conn As New SAConnection("Data Source=Sybase IQ Demo")
Dim cmd As New SACommand("SELECT Surname FROM Employees", conn)
Dim reader As SADataReader
conn.Open()
reader = cmd.ExecuteReader()
ListEmployees.BeginUpdate()
Do While (reader.Read())
    ListEmployees.Items.Add(reader.GetString(0))
Loop
ListEmployees.EndUpdate()
conn.Close()

C# ExecuteScalar Example

The following C# code opens a connection to the SAP Sybase IQ sample database and uses the ExecuteScalar method to obtain a count of the number of male employees in the Employees table:

SAConnection conn = new SAConnection("Data Source=Sybase IQ Demo");
conn.Open();
SACommand cmd = new SACommand(
    "SELECT COUNT(*) FROM Employees WHERE Sex = 'M'", conn );
int count = (int) cmd.ExecuteScalar();
textBox1.Text = count.ToString();
conn.Close();