Documentation Home
Connectors and APIs Manual
Download this Manual

4.5.2 Using MySqlCommand

A MySqlCommand has the CommandText and CommandType properties associated with it. The CommandText will be handled differently depending on the setting of CommandType. CommandType can be one of:

  • Text - An SQL text command (default)

  • StoredProcedure - The name of a Stored Procedure

  • TableDirect - The name of a table

The default CommandType, Text, is used for executing queries and other SQL commands. Some example of this can be found in the following section Section, “The MySqlCommand Object”.

If CommandType is set to StoredProcedure, set CommandText to the name of the Stored Procedure to access.

If CommandType is set to TableDirect, all rows and columns of the named table will be returned when you call one of the Execute methods. In effect, this command performs a SELECT * on the table specified. The CommandText property is set to the name of the table to query. This is illustrated by the following code snippet:

MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "mytable";
cmd.Connection = someConnection;
cmd.CommandType = CommandType.TableDirect;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
   Console.WriteLn(reader[0], reader[1]...);

Examples of using the CommandType of StoredProcedure can be found in the section Section 4.5.6, “Accessing Stored Procedures with Connector/NET”.

Commands can have a timeout associated with them. This is useful as you may not want a situation were a command takes up an excessive amount of time. A timeout can be set using the CommandTimeout property. The following code snippet sets a timeout of one minute:

MySqlCommand cmd = new MySqlCommand();
cmd.CommandTimeout = 60;

The default value is 30 seconds. Avoid a value of 0, which indicates an indefinite wait. To change the default command timeout, use the connection string option Default Command Timeout.

Connector/NET supports timeouts that are aligned with how Microsoft handles SqlCommand.CommandTimeout. This property is the cumulative timeout for all network reads and writes during command execution or processing of the results. A timeout can still occur in the MySqlReader.Read method after the first row is returned, and does not include user processing time, only IO operations.

Further details on this can be found in the relevant Microsoft documentation.