All pages
Powered by GitBook
1 of 39

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

MariaDB Connector/C API Prepared Statement Functions

Explore API functions for prepared statements in Connector/C. This section provides detailed documentation on using prepared statements for efficient and secure query execution in C applications.

mysql_stmt_affected_rows

Syntax

my_ulonglong mysql_stmt_affected_rows(MYSQL_STMT * stmt);
  • stmt - a statement handle, which was previously allocated by mysql_stmt_init().

Description

Returns the number of affected rows by the last prepared statement associated with mysql, if the operation was an "upsert" (, , or ) statement, or -1 if the last prepared statement failed.

When using UPDATE, MariaDB will not update columns where the new value is the same as the old value. This creates the possibility that mysql_stmt_affected_rows() may not equal the number of rows matched, only the number of rows that were literally affected by the query.

The statement first deletes the record with the same primary key and then inserts the new record. This function returns the number of deleted records in addition to the number of inserted records.

See Also

mariadb_stmt_fetch_fields

Syntax

  • stmt - A statement handle, which was previously allocated by .

Description

Returns an array of fields. Each field contains the definition for a column of the result set. If the statement doesn't have a result set a NULL pointer will be returned.

This function was added in Connector/C 3.1.0

The number of fields can be obtained by mysql_stmt_field_count()

See Also

  • mysql_stmt_field_count()

MYSQL_FIELD *mariadb_stmt_fetch_fields(MYSQL_STMT * stmt);
mysql_stmt_init()
mysql_stmt_insert_id()

mysql_stmt_bind_result

Syntax

  • stmt - a statement handle, which was previously allocated by mysql_stmt_init().

  • bind - an array of structures. The size of this array must be equal to the number of columns in result set.

Description

Binds columns in the result set to variables. Returns zero on success, non-zero on failure.

To determine the number of columns in result set use .

A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time is called.

See Also

my_bool mysql_stmt_bind_result(MYSQL_STMT * stmt,
                               MYSQL_BIND * bind);

Connector C Data Structures and Definitions

Explore practical examples of prepared statements. Learn how to use them to enhance application security against SQL injection and improve query performance by optimizing statement execution.

Prepared Statement Examples

Prepared statement examples

MYSQL_BIND
mysql_stmt_field_count()
mysql_stmt_fetch()
mysql_stmt_field_count()
mysql_stmt_execute()
mysql_stmt_fetch()

mysql_stmt_data_seek

Syntax

void mysql_stmt_data_seek(MYSQL_STMT * stmt,
                          my_ulonglong offset);
  • stmt - a statement handle, which was previously allocated by mysql_stmt_init().

  • offset - row offset. This value must between 0 and number of rows - 1.

Description

Seeks to an arbitrary row in statement result set obtained by a previous call to . Returns void.

The number of rows can be obtained with the function .

See Also

mysql_stmt_row_seek

Syntax

MYSQL_ROW_OFFSET mysql_stmt_row_seek(MYSQL_STMT * stmt,
     MYSQL_ROW_OFFSET offset);
  • stmt - a statement handle, which was previously allocated by mysql_stmt_init().

  • offset - row offset. This value can be obtained either by mysql_stmt_row_seek() or .

Description

Positions the row cursor to an arbitrary row in a result set which was obtained by . Returns the previous row offset.

The result set must be obtained by .

See Also

mariadb_stmt_execute_direct

Syntax

  • stmt - A statement handle, which was previously allocated by mysql_stmt_init().

  • query SQL statement

  • length Length of SQL statement

Description

Prepares and executes a statement which was previously allocated by , using the current values of the parameter variables if any parameters exist in the statement.

Returns zero on success, non-zero on failure.

This function was added in Connector/C 3.0 and requires or later versions.

  • Since the number of parameter of the statement is unknown before execution it is mandatory to set the number of parameters via the function.

  • If the SQL statement is a zero-terminated string, you can also pass -1 as length.

  • The statement handle is intended for one-time execution. Reusing the statement handle might lead to unexpected behavior.

See Also

Example

mysql_stmt_fetch

Syntax

int mysql_stmt_fetch(MYSQL_STMT * stmt);
  • stmt - a statement handle, which was previously allocated by mysql_stmt_init().

Description

Fetch the result from a prepared statement into the buffer bound by mysql_stmt_bind_result(). Returns 0 for success, MYSQL_NO_DATA if the end of the result set has been reached, or MYSQL_DATA_TRUNCATED if one or more values are truncated.

Note that all columns must be bound by the application before calling mysql_stmt_fetch().

Data are transferred unbuffered without calling which can decrease performance (but reduces memory cost).

See Also

mysql_stmt_param_metadata

Syntax

MYSQL_RES * mysql_stmt_param_metadata(MYSQL_STMT * stmt);
  • stmt - a statement handle, which was previously allocated by mysql_stmt_init().

mysql_stmt_field_count

Syntax

unsigned int mysql_stmt_field_count(MYSQL_STMT * stmt);
  • stmt - a statement handle, which was previously allocated by mysql_stmt_init().

Description

Returns the number of fields in a result set of a prepared statement.

The number of fields will be available after calling

mysql_stmt_field_count() returns zero for UPSERT statements which don't produce a result set.

See Also

mysql_stmt_errno

Syntax

unsigned int mysql_stmt_errno(MYSQL_STMT * stmt);
  • stmt - a statement handle, which was previously allocated by mysql_stmt_init().

Description

Returns the for the most recently invoked statement function that can succeed or fail. Zero means no error occurred.

Client error messages are listed in errmsg.h header file, server error messages are listed in mysqld_error.h header file of the server source distribution.

See Also

  • ,

mysql_stmt_execute

Syntax

  • stmt - A statement handle, which was previously allocated by .

mysql_stmt_insert_id

Syntax

  • stmt - a statement handle, which was previously allocated by .

mysql_stmt_next_result

Syntax

  • stmt - a statement handle, which was previously allocated by .

mysql_stmt_warning_count

Syntax

  • stmt - a statement handle, which was previously allocated by .

MYSQL_STMT

The MYSQL_STMT structure is a handle for a prepared statement. The handle will be allocated by and released by .

  • All members of MYSQL_STMT are private and not intended for application use.

  • Multiple statement handles can be opened within the same connection.

mysql_stmt_free_result

Syntax

  • stmt - a statement handle, which was previously allocated by .

mysql_stmt_row_tell

Syntax

  • stmt - a statement handle, which was previously allocated by .

mysql_stmt_param_count

Syntax

  • stmt - a statement handle, which was previously allocated by .

mysql_stmt_close

Syntax

  • stmt - a statement handle, which was previously allocated by .

int mariadb_stmt_execute_direct(MYSQL_STMT * stmt, const char *query, size_t length);
mysql_stmt_store_result()
mysql_stmt_num_rows()
mysql_stmt_row_tell()
mysql_stmt_store_result()
mysql_stmt_num_rows()
mysql_stmt_row_tell()
mysql_stmt_store_result()
mysql_use_result()
mysql_stmt_row_tell()
mysql_stmt_store_result
mysql_stmt_store_result()
mysql_stmt_prepare()
mysql_stmt_bind_result()
mysql_stmt_execute()
mysql_stmt_prepare()
mysql_stmt_prepare()
mysql_stmt_param_count()
After a successful call to mysql_stmt_prepare() a prepared statement will also allocate resources on the server.
  • Closing the connection with mysql_close() invalidates the statements but doesn't free resources on the client.

  • mysql_stmt_init()
    mysql_stmt_close()
    int mysql_stmt_next_result(MYSQL_STMT * stmt);
    mysql_stmt_init()
    Description

    Frees stored result memory of a prepared statement. Returns void.

    See Also

    • mysql_stmt_store_result()

    my_bool mysql_stmt_free_result(MYSQL_STMT * stmt);
    mysql_stmt_init()
    Description

    Returns the row offset of a result cursor. The returned offset value can be used to reposition the result cursor by calling mysql_stmt_row_seek().

    This function can be used for buffered result sets only, which can be obtained by executing the mysql_stmt_store_result() function.

    See Also

    • mysql_stmt_row_seek()

    • mysql_stmt_store_result()

    mysql_stmt_init()
    Description

    Returns the number of parameter markers present in the prepared statement.

    This function will not deliver a valid result until mysql_stmt_prepare() was called.

    See Also

    • mysql_stmt_prepare()

    • mysql_stmt_field_count()

    mysql_stmt_init()
    Description

    Closes a prepared statement and deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.

    Returns zero on success, nonzero on error (when communicating with the server). The statement is deallocated, regardless of the error.

    If you want to reuse the statement handle with a different SQL command, use mysql_stmt_reset().

    See Also

    • mysql_stmt_init()

    • mysql_stmt_reset()

    mysql_stmt_init()
    MYSQL_ROW_OFFSET mysql_stmt_row_tell(MYSQL_STMT * stmt);
    unsigned long mysql_stmt_param_count(MYSQL_STMT * stmt);
    my_bool mysql_stmt_close(MYSQL_STMT * stmt);
    Description

    Executes a prepared statement which was previously prepared by mysql_stmt_prepare(). When executed any parameter markers which exist will automatically be replaced with the appropriate data.

    Returns zero on success, non-zero on failure.

    If the statement is , , or , the total number of affected rows can be determined by using the mysql_stmt_affected_rows() function. Likewise, if the query yields a result set, the mysql_stmt_fetch() function is used.

    See Also

    • mariadb_stmt_execute_direct()

    • mysql_stmt_prepare()

    • mysql_stmt_bind_param()

    • mysql_stmt_next_result()

    mysql_stmt_init()
    Description

    The mysql_stmt_insert_id() function returns the ID generated by a prepared statement on a table with a column having the attribute. If the last query wasn't an or statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.

    When performing a multi-insert prepared statement, mysql_stmt_insert_id() will return the value of the first row.

    See Also

    • mysql_insert_id()

    my_ulonglong mysql_stmt_insert_id(MYSQL_STMT * stmt);
    mysql_stmt_init()
    Description

    Returns the number of warnings from the last executed statement, or zero if there are no warnings. This function was added in Connector/C 3.0.

    For retrieving warning messages you should use the SQL command SHOW WARNINGS. If TRADITIONAL is enabled an error instead of warning will be returned. For detailed information check the server documentation.

    See Also

    • mysql_warning_count()

    mysql_stmt_init()
    mysql_stmt_init()
    mysql_stmt_attr_set()
    mysql_stmt_attr_set()
    mysql_stmt_bind_param()
    mysql_stmt_error()
    mysql_stmt_sqlstate()

    mysql_stmt_attr_get

    Syntax

    • stmt - a statement handle, which was previously allocated by mysql_stmt_init().

    • enum_stmt_attr_type - attribute. See below.

    • attr - pointer to a variable, which will contain the attribute value.

    Description

    Gets the current value of a statement attribute. Returns zero on success, non zero on failure.

    Attribute types

    The enum_stmt_attr_type parameter has the following possible values:

    • STMT_ATTR_UPDATE_MAX_LENGTH: Indicates if will update the max_length value of MYSQL_FIELD structures.

    • STMT_ATTR_CURSOR_TYPE: Cursor type. Possible values are CURSOR_TYPE_READ_ONLY or default value CURSOR_TYPE_NO_CURSOR.

    • STMT_ATTR_PREFETCH_ROWS

    Setting the number of prefetched rows will work only for read only cursors.

    See Also

    mysql_stmt_reset

    Syntax

    my_bool mysql_stmt_reset(MYSQL_STMT * stmt);
    • stmt - a statement handle, which was previously allocated by mysql_stmt_init(). Returns zero on success, nonzero if an error occurred.

    Description

    Resets a prepared statement on the client and server to state after prepare.

    mysql_stmt_reset() resets the statement on the server, unbuffered result sets, and errors. Bindings and stored result sets will not be cleared. The latter one will be cleared when re-executing or closing the prepared statement. To reprepare a prepared statement with another SQL statement, use .

    See Also

    mysql_stmt_prepare

    Syntax

    • stmt - a statement handle, which was previously allocated by mysql_stmt_init().

    • query - SQL statement

    • length - length of SQL statement

    Description

    Prepares the SQL query pointed to by the null-terminated string query. Returns zero on success, non-zero on failure.

    The parameter markers must be bound to application variables using .

    The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an statement (to specify column values for a row), or in a comparison with a column in a clause to specify a comparison value.

    However, they are not allowed for (such as table or column names), in the select list that names the columns to be returned by a statement), or to specify both operands of a binary operator such as the sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Language (DML) statements, and not in Data Definition Language (DDL) statements.

    See Also

    mysql_stmt_error

    Syntax

    const char * mysql_stmt_error(MYSQL_STMT * stmt);
    • stmt - a statement handle, which was previously allocated by mysql_stmt_init().

    Description

    Returns a string containing the error message for the most recently invoked statement function that can succeed or fail. The string will be empty if no error occurred.

    Client error messages are listed in the errmsg.h header file, server error messages are listed in the mysqld_error.h header file of the server source distribution.

    See Also

    mysql_stmt_init

    Syntax

    • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

    Description

    Initializes and allocates memory for a prepared statement. Returns a pointer to a MYSQL_STMT structure or NULL if an error occurred.

    Members of the MYSQL_STMT structure are not intended for application use.\

    A statement handles which was allocated by mysql_stmt_init() needs to be freed with .\

    Any subsequent calls to any mysql_stmt function will fail until was called.

    See Also

    mysql_stmt_result_metadata

    Syntax

    MYSQL_RES * mysql_stmt_result_metadata(MYSQL_STMT * stmt);
    • stmt - a statement handle, which was previously allocated by mysql_stmt_init().

    Description

    If a statement passed to is one that produces a result set, mysql_stmt_result_metadata() returns the result set that can be used to process the meta information such as the total number of fields and individual field information.

    The result set returned by mysql_stmt_result_metadata() contains only metadata. It does not contain any row results. The rows are obtained by . This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata, such as: , , , , , , ,

    See Also

    Connector/C Types and Definitions

    Field types

    Field types are used in the MYSQL_BIND structure and represent the type of the fields. Field types are defined in mariadb_com.h.

    • MYSQL_TYPE_BIT

    • MYSQL_TYPE_BLOB

    • MYSQL_TYPE_DATE

    • MYSQL_TYPE_DATETIME

    • MYSQL_TYPE_DECIMAL

    • MYSQL_TYPE_DOUBLE

    • MYSQL_TYPE_ENUM

    • MYSQL_TYPE_FLOAT

    • MYSQL_TYPE_GEOMETRY

    • MYSQL_TYPE_INT24

    • MYSQL_TYPE_JSON

    • MYSQL_TYPE_LONG

    • MYSQL_TYPE_LONGLONG

    • MYSQL_TYPE_LONG_BLOB

    • MYSQL_TYPE_MEDIUM_BLOB

    • MYSQL_TYPE_NEWDATE

    • MYSQL_TYPE_NEWDECIMAL

    • MYSQL_TYPE_NULL

    • MYSQL_TYPE_SET

    • MYSQL_TYPE_SHORT

    • MYSQL_TYPE_STRING

    • MYSQL_TYPE_TIME

    • MYSQL_TYPE_TIMESTAMP

    • MYSQL_TYPE_TINY

    • MYSQL_TYPE_TINY_BLOB

    • MYSQL_TYPE_VARCHAR

    • MYSQL_TYPE_VAR_STRING

    • MYSQL_TYPE_YEAR

    Indicator variables

    Indicator variables store supplementary information which will be sent to the server.

    mysql_stmt_store_result

    Syntax

    • stmt - a statement handle, which was previously allocated by .

    mysql_stmt_bind_param

    Syntax

    • stmt - a statement handle, which was previously allocated by .

    • bind

    mysql_stmt_num_rows

    Syntax

    • stmt - a statement handle, which was previously allocated by .

    int mysql_stmt_execute(MYSQL_STMT * stmt);
    unsigned int mysql_stmt_warning_count(MYSQL_STMT * stmt);
    static int execute_direct_example(MYSQL *mysql)
    {
      MYSQL_STMT *stmt= mysql_stmt_init(mysql);
      MYSQL_BIND bind[2];
      int intval= 1;
      int param_count= 2;
      char *strval= "execute_direct_example";
    
      /* Direct execution without parameters */
      if (mariadb_stmt_execute_direct(stmt, "CREATE TABLE execute_direct (a int, b varchar(30))", -1))
        goto error;
    
      memset(&bind, 0, sizeof(MYSQL_BIND) * 2);
      bind[0].buffer_type= MYSQL_TYPE_SHORT;
      bind[0].buffer= &intval;
      bind[1].buffer_type= MYSQL_TYPE_STRING;
      bind[1].buffer= strval;
      bind[1].buffer_length= strlen(strval);
    
      /* set number of parameters */
      if (mysql_stmt_attr_set(stmt, STMT_ATTR_PREBIND_PARAMS, &param_count))
        goto error;
    
      /* bind parameters */
      if (mysql_stmt_bind_param(stmt, bind))
        goto error;
    
      if (mariadb_stmt_execute_direct(stmt, "INSERT INTO execute_direct VALUES (?,?)", -1))
        goto error;
    
      mysql_stmt_close(stmt);
      return 0;
    error:
      printf("Error: %s\n", mysql_stmt_error(stmt));
      mysql_stmt_close(stmt);
      return 1;
    }
    my_bool mysql_stmt_attr_get(MYSQL_STMT * stmt,
                                enum enum_stmt_attr_type,
                                void * attr);
    int mysql_stmt_prepare(MYSQL_STMT * stmt,
                           const char * query,
                           unsigned long length);
    MYSQL_STMT * mysql_stmt_init(MYSQL * mysql);
    mysql_stmt_prepare()
    mysql_stmt_close()
    mysql_stmt_prepare()
    mysql_stmt_execute()
    mysql_stmt_bind_param()
    INSERT
    WHERE
    identifiers
    SELECT
    = (equal)
    mysql_stmt_init()
    mysql_stmt_param_count()
    mysql_stmt_execute()
    mysql_stmt_errno()
    mysql_stmt_sqlstate()
    mysql_stmt_close()
    mysql_stmt_prepare()
    mysql_stmt_close()
    mysql_stmt_prepare()
    mysql_stmt_prepare()
    mysql_stmt_fetch()
    mysql_num_fields()
    mysql_fetch_field()
    mysql_fetch_field_direct()
    mysql_fetch_fields()
    mysql_field_count()
    mysql_field_seek()
    mysql_field_tell()
    mysql_free_result()
    mariadb_stmt_fetch_fields()
    mysql_free_result()
    mysql_stmt_prepare()

    STMT_INDICATOR_NONE

    no indicator (=0)

    STMT_INDICATOR_NTS

    (string) buffer is null/zero terminated string

    STMT_INDICATOR_NULL

    buffer is null

    STMT_INDICATOR_DEFAULT

    use columns default value

    STMT_INDICATOR_IGNORE

    do not update column value

    Description

    Returns the number of rows in the result set. The use of mysql_stmt_num_rows() depends on whether or not you used mysql_stmt_store_result() to buffer the entire result set in the statement handle.

    If you use mysql_stmt_store_result(), mysql_stmt_num_rows() may be called immediately.

    See Also

    • mysql_stmt_store_result()

    mysql_stmt_init()
    : Number of rows which will be prefetched. The default value is 1.
  • STMT_ATTR_PREBIND_PARAMS: Number of parameters used for mariadb_stmt_execute_direct()

  • mysql_stmt_store_result()
    mysql_stmt_attr_set()
    unsigned long long mysql_stmt_num_rows(MYSQL_STMT * stmt);
    unsigned int param_count;
    rc= mysql_stmt_attr_get(stmt, STMT_ATTR_PREBIND_PARAMS, ¶m_count);
    my_bool is_update;
    rc= mysql_stmt_attr_get(stmt, STMT_ATTR_UPDATE_MAX_LENGTH, &is_update);
    unsigned long cursor_type;
    rc= mysql_stmt_attr_get(stmt, STMT_ATTR_CURSOR_TYPE, &cursor_type);
    unsigned long prefetch_rows;
    rc= mysql_stmt_attr_get(stmt, STMT_ATTR_PREFETCH_ROWS, &prefetch_rows);
    Description

    You must call mysql_stmt_store_result() for every query that successfully produces a result set (, , , ), and only if you want to buffer the complete result set by the client, so that the subsequent mysql_stmt_fetch() call returns buffered data.

    Returns zero on success, nonzero if an error occurred.

    You can detect whether the statement produced a result set by checking the return value of mysql_stmt_result_metadata() function.

    See Also

    • mysql_stmt_result_metadata()

    • mysql_stmt_fetch()

    mysql_stmt_init()
    - an array of MYSQL_BIND structures. The size of this array must be equal to the number of parameters.

    Description

    Binds variables for parameter markers in the prepared statement that was passed to mysql_stmt_prepare(). Returns zero on success, non-zero on failure.

    • The number of parameters can be obtained by mysql_stmt_param_count().

    • If the number of parameters is unknown, for example when using mariadb_stmt_execute_direct(), the number of parameters have to be specified with the mysql_stmt_attr_set() function.

    See Also

    • mariadb_stmt_execute_direct()

    • mysql_stmt_prepare()

    • mysql_stmt_bind_result()

    • mysql_stmt_execute()

    mysql_stmt_init()

    mysql_stmt_attr_set

    Syntax

    • stmt - a statement handle, which was previously allocated by mysql_stmt_init().

    • enum_stmt_attr_type - the attribute that you want to set. See below.

    • attr - the value to assign to the attribute

    Description

    Used to modify the behavior of a prepared statement. This function may be called multiple times to set several attributes. Returns zero on success, non-zero on failure.

    Attribute types

    The enum_stmt_attr_type attribute can have one of the following values:

    • STMT_ATTR_UPDATE_MAX_LENGTH If set to 1, will update the max_length value of MYSQL_FIELD structures.

    • STMT_ATTR_CURSOR_TYPE: cursor type when is invoked. Possible values are CURSOR_TYPE_READ_ONLY or default value CURSOR_TYPE_NO_CURSOR.

    • STMT_ATTR_PREFETCH_ROWS: number of rows which will be prefetched. The default value is 1.

    • STMT_ATTR_PREBIND_PARAMS: number of parameter markers when using . If the statement handle is reused it will be reset automatically to the state after mysql_stmt_init(). This option was added in Connector/C 3.0

    • STMT_ATTR_ARRAY_SIZE: number of array elements. This option was added in Connector/C 3.0 and requires or later

    • STMT_ATTR_ROW_SIZE: specifies size of a structure for row wise binding. This length must include space for all of the bound parameters and any padding of the structure or buffer to ensure that when the address of a bound parameter is incremented with the specified length, the result will point to the beginning of the same parameter in the next set of parameters. When using the sizeof operator in ANSI C, this behavior is guaranteed. If the value is zero column-wise binding will be used (default). This option was added in Connector/C 3.0 and requires or later

    • If you use the MYSQL_STMT_ATTR_CURSOR_TYPE option with MYSQL_CURSOR_TYPE_READ_ONLY, a cursor is opened for the statement when you invoke . If there is already an open cursor from a previous call, it closes the cursor before opening a new one. also closes any open cursor before preparing the statement for re-execution.

    • If you open a cursor for a prepared statement, it is unnecessary to call .

    See Also

    mysql_stmt_send_long_data

    Syntax

    my_bool mysql_stmt_send_long_data(MYSQL_STMT * stmt,
                                      unsigned int,
                                      const char * data,
                                      unsigned long);
    • stmt - a statement handle, which was previously allocated by mysql_stmt_init().

    • param_no - indicates which parameter to associate the data with. Parameters are numbered beginning with 0.

    • data - a buffer containing the data to send.

    • long - size of the data buffer.

    Description

    Allows sending parameter data to the server in pieces (or chunks), e.g. if the size of a blob exceeds the size of . This function can be called multiple times to send the parts of a character or binary data value for a column, which must be one of the or datatypes.

    Returns zero on success, nonzero if an error occurred.

    mysql_stmt_fetch_column

    Syntax

    • stmt - a statement handle, which was previously allocated by mysql_stmt_init().

    • bind_arg - a pointer to a MYSQL_BIND structure.

    • column - number of columns, first column is numbered zero.

    • offset - offset at which to begin retrieving data.

    Description

    This function can be used to fetch large data of a single column in pieces. Returns zero on success, non-zero on failure.

    The size of the buffer is specified within MYSQL_BIND structure.

    See Also

    Bulk Insert (Column-wise Binding)

    The following example uses indicator variables and column-wise binding to insert an array of data.

    Now we can check the content of table bulk_example1:

    mysql_stmt_sqlstate

    Syntax

    • stmt - a statement handle, which was previously allocated by .

    int mysql_stmt_store_result(MYSQL_STMT * stmt);
    my_bool mysql_stmt_bind_param(MYSQL_STMT * stmt,
                                  MYSQL_BIND * bnd);
    my_bool mysql_stmt_attr_set(MYSQL_STMT * stmt,
                                enum enum_stmt_attr_type,
                                const void * attr);
    int mysql_stmt_fetch_column(MYSQL_STMT * stmt,
                                MYSQL_BIND * bind_arg,
                                unsigned int column,
                                unsigned long offset);
    mysql_stmt_param_count()
    mysql_stmt_send_long_data()
    mysql_stmt_fetch()
    mysql_stmt_send_long_data()
    #include <mysql.h>
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    static void show_mysql_error(MYSQL *mysql)
    {
      printf("Error(%d) [%s] \"%s\"", mysql_errno(mysql),
                                      mysql_sqlstate(mysql),
                                      mysql_error(mysql));
      exit(-1);
    }
    
    static void show_stmt_error(MYSQL_STMT *stmt)
    {
      printf("Error(%d) [%s] \"%s\"", mysql_stmt_errno(stmt),
                                      mysql_stmt_sqlstate(stmt),
                                      mysql_stmt_error(stmt));
      exit(-1);
    }
    
    int main(int argc, char *argv[])
    {
      MYSQL *mysql;
      MYSQL_STMT *stmt;
      MYSQL_BIND bind[3];
    
      /* Data for insert */
      const char *surnames[]= {"Widenius", "Axmark", "N.N."};
      unsigned long surnames_length[]= {8,6,4};
      const char *forenames[]= {"Monty", "David", "will be replaced by default value"};
      char forename_ind[]= {STMT_INDICATOR_NTS, STMT_INDICATOR_NTS, STMT_INDICATOR_DEFAULT};
      char id_ind[]= {STMT_INDICATOR_NULL, STMT_INDICATOR_NULL, STMT_INDICATOR_NULL};
      unsigned int array_size= 3; 
    
      mysql= mysql_init(NULL);
    
      /* connect to MariaDB server */
      if (!mysql_real_connect(mysql, "localhost", "example", "example_pw", 
                              "example_db", 0, "/tmp/mysql.sock", 0))
        show_mysql_error(mysql);
    
      if (mysql_query(mysql, "DROP TABLE IF EXISTS bulk_example1"))
        show_mysql_error(mysql);
    
      if (mysql_query(mysql, "CREATE TABLE bulk_example1 (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,"\
                             "forename CHAR(30) NOT NULL DEFAULT 'unknown', surname CHAR(30))"))
        show_mysql_error(mysql);
    
      stmt= mysql_stmt_init(mysql);
      if (mysql_stmt_prepare(stmt, "INSERT INTO bulk_example1 VALUES (?,?,?)", -1))
        show_stmt_error(stmt);
    
      memset(bind, 0, sizeof(MYSQL_BIND) * 3);
    
      /* We autogenerate id's, so all indicators are STMT_INDICATOR_NULL */
      bind[0].u.indicator= id_ind;
      bind[0].buffer_type= MYSQL_TYPE_LONG;
    
      bind[1].buffer= forenames;
      bind[1].buffer_type= MYSQL_TYPE_STRING;
      bind[1].u.indicator= forename_ind;
    
      bind[2].buffer_type= MYSQL_TYPE_STRING;
      bind[2].buffer= surnames;
      bind[2].length= &surnames_length;
    
      /* set array size */
      mysql_stmt_attr_set(stmt, STMT_ATTR_ARRAY_SIZE, &array_size);
    
      /* bind parameter */
      mysql_stmt_bind_param(stmt, bind);
    
      /* execute */
      if (mysql_stmt_execute(stmt))
        show_stmt_error(stmt);
    
      mysql_stmt_close(stmt);
      mysql_close(mysql);
    }
    Description

    Returns a string containing the SQLSTATE error code for the most recently invoked prepared statement function that can succeed or fail. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC.

    Please note that not all client library error codes are mapped to SQLSTATE errors. Errors which can't be mapped will returned as value HY000.

    See Also

    • mysql_errno()

    • mysql_error()

    mysql_stmt_init()

    Bulk Insert (Row-wise Binding)

    The following example uses indicator variables and row-wise binding to insert an array of structures.

    Now we can check the content of table bulk_example2:

    MariaDB [example_db]> SELECT id,forename,surname FROM bulk_example2;
    +----+----------+----------+
    | id | forename | surname  |
    +----+----------+----------+
    |  1 | Monty    | Widenius |
    |  2 | David    | Axmark   |
    |  3 | unknown  | N.N.     |
    +----+----------+----------+
    MariaDB [example_db]> SELECT id,forename,surname FROM bulk_example1;
    +----+----------+----------+
    | id | forename | surname  |
    +----+----------+----------+
    |  1 | Monty    | Widenius |
    |  2 | David    | Axmark   |
    |  3 | unknown  | N.N.     |
    +----+----------+----------+
    const char * mysql_stmt_sqlstate(MYSQL_STMT * stmt);
    #include <mysql.h>
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    static void show_mysql_error(MYSQL *mysql)
    {
      printf("Error(%d) [%s] \"%s\"", mysql_errno(mysql),
                                      mysql_sqlstate(mysql),
                                      mysql_error(mysql));
      exit(-1);
    }
    
    static void show_stmt_error(MYSQL_STMT *stmt)
    {
      printf("Error(%d) [%s] \"%s\"", mysql_stmt_errno(stmt),
                                      mysql_stmt_sqlstate(stmt),
                                      mysql_stmt_error(stmt));
      exit(-1);
    }
    
    int main(int argc, char *argv[])
    {
      MYSQL *mysql;
      MYSQL_STMT *stmt;
      MYSQL_BIND bind[3];
    
      struct st_data {
        unsigned long id;
        char id_ind;
        char forename[30];
        char forename_ind;
        char surname[30];
        char surname_ind;
      };
    
      struct st_data data[]= {
        {0, STMT_INDICATOR_NULL, "Monty", STMT_INDICATOR_NTS, "Widenius", STMT_INDICATOR_NTS},
        {0, STMT_INDICATOR_NULL, "David", STMT_INDICATOR_NTS, "Axmark", STMT_INDICATOR_NTS},
        {0, STMT_INDICATOR_NULL, "default", STMT_INDICATOR_DEFAULT, "N.N.", STMT_INDICATOR_NTS},
      };
    
      unsigned int array_size= 3;
      size_t row_size= sizeof(struct st_data);
    
      mysql= mysql_init(NULL);
    
      /* connect to MariaDB server */
      if (!mysql_real_connect(mysql, "localhost", "example", "example_pw", 
                              "example_db", 0, "/tmp/mysql.sock", 0))
        show_mysql_error(mysql);
    
      if (mysql_query(mysql, "DROP TABLE IF EXISTS bulk_example2"))
        show_mysql_error(mysql);
    
      if (mysql_query(mysql, "CREATE TABLE bulk_example2 (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,"\
                             "forename CHAR(30) NOT NULL DEFAULT 'unknown', surname CHAR(30))"))
        show_mysql_error(mysql);
    
      stmt= mysql_stmt_init(mysql);
      if (mysql_stmt_prepare(stmt, "INSERT INTO bulk_example2 VALUES (?,?,?)", -1))
        show_stmt_error(stmt);
    
      memset(bind, 0, sizeof(MYSQL_BIND) * 3);
    
      /* We autogenerate id's, so all indicators are STMT_INDICATOR_NULL */
      bind[0].u.indicator= &data[0].id_ind;
      bind[0].buffer_type= MYSQL_TYPE_LONG;
    
      bind[1].buffer= &data[0].forename;
      bind[1].buffer_type= MYSQL_TYPE_STRING;
      bind[1].u.indicator= &data[0].forename_ind;
    
      bind[2].buffer_type= MYSQL_TYPE_STRING;
      bind[2].buffer= &data[0].surname;
      bind[2].u.indicator= &data[0].surname_ind;
    
      /* set array size */
      mysql_stmt_attr_set(stmt, STMT_ATTR_ARRAY_SIZE, &array_size);
    
      /* set row size */
      mysql_stmt_attr_set(stmt, STMT_ATTR_ROW_SIZE, &row_size);
    
      /* bind parameter */
      mysql_stmt_bind_param(stmt, bind);
    
      /* execute */
      if (mysql_stmt_execute(stmt))
        show_stmt_error(stmt);
    
      mysql_stmt_close(stmt);
      mysql_close(mysql);
    }

    mysql_stmt_free_result() closes any open cursor.

    mysql_stmt_store_result()
    mysql_stmt_execute()
    mariadb_stmt_execute_direct()
    mysql_stmt_execute()
    mysql_stmt_execute()
    mysql_stmt_reset()
    mysql_stmt_store_result()
    mariadb_stmt_execute_direct()
    mysql_stmt_attr_get()

    MYSQL_BIND

    The MYSQL_BIND structure is used to bind parameters (which will be sent to the server) and result sets (output sent from server to client). The MYSQL_BIND structure is bound with mysql_stmt_bind_param() or mysql_stmt_bind_result() to a prepared statement.

    Members of MYSQL_BIND structure

    • enum enum_field_types field_type: Type of the buffer for in- or output. For a complete list of types see the section.

    • void buffer: Address of a variable, array or structure used for data transfer.

    • unsigned long buffer_length: Size of buffer in bytes.

    • unsigned long * length: Pointer to a length variable for output or array of length elements for input (array binding).

    • my_bool * error: Pointer to an error variable for output.

    • my_bool * is_null: Pointer to a null indicator for output.

    • char * u.indicator: Array of indicator variables for input (array binding)

    • my_bool is_unsigned: Set when numeric data type is unsigned

    Array binding

    Array binding for bulk insert/updates was introduced with Connector/C 3.0 and requires or above. It allows clients to control the number of rows that will be physically transferred between the server and the client in one logical bind or fetch. This can greatly improve the performance of many applications by trading buffer space for time (network traffic) and is a better and more secure alternative to LOAD DATA LOCAL INFILE, especially when the data will be generated within application.

    Indicator variables

    Indicator variables are used to represent special semantics like NULL or DEFAULT values.

    Column wise binding

    When using column wise binding (the default) the application binds up to 3 arrays to a column: a data array, a length array and optionally an indicator array.

    The number of rows has to be set by calling with the STMT_ATTR_ARRAY_SIZE option:

    Each array contains as many elements as specified in the array_size parameter.

    An example for column wise binding can be found .

    Row wise binding

    When using row wise binding the application binds up to 3 elements of a structure to a column: a data element, a length element and an optional indicator element.

    The application declares the size of the structure with the STMT_ATTR_ROW_SIZE attribute and binds the address of each member in the first element of the array:

    Connector/C can now calculate the address of the data for a particular row and column asaddress= bind_address + row_nr * row_size where rows are numbered from 0 to size of rowset - 1.

    If row_size is zero, column wise binding will be used instead.

    An example for row wise binding can be found .

    my_bool update= 1;
    rc= mysql_stmt_attr_set(stmt, STMT_ATTR_UPDATE_MAX_LENGTH, &update);
    unsigned long cursor_type= CURSOR_TYPE_READ_ONLY;
    rc= mysql_stmt_attr_set(stmt, STMT_ATTR_CURSOR_TYPE, &cursor_type);
    unsigned long rows=4;
    rc= mysql_stmt_attr_set(stmt, STMT_ATTR_PREFETCH_ROWS, &rows);
    unsigned int params= 5;
    rc= mysql_stmt_attr_set(stmt, STMT_ATTR_PREBIND_PARAMS, ¶ms);
    unsigned int array_size= 5;
    rc= mysql_stmt_attr_set(stmt, STMT_ATTR_ARRAY_SIZE, &array_size);
    size_t row_size= sizeof(struct st_customer);
    rc= mysql_stmt_attr_set(stmt, STMT_ATTR_ROW_SIZE, &array_size);

    Indicator variable

    Description

    STMT_INDICATOR_NTS

    String is null terminated

    STMT_INDICATOR_NONE

    No semantics

    STMT_INDICATOR_NULL

    NULL value

    STMT_INDICATOR_DEFAULT

    Use columns default value

    STMT_INDICATOR_IGNORE

    Skip update of column

    types and definitions
    mysql_stmt_attr_set()
    here
    here
    column_wise_binding
    row_wise_binding
    unsigned int array_size= 100;
      mysql_stmt_attr_set(stmt, STMT_ATTR_ARRAY_SIZE, array_size);
    unsigned int row_size= sizeof(struct my_data);
    mysql_stmt_attr_set(stmt, STMT_ATTR_ROW_SIZE, &row_size);
    MariaDB 10.2
    MariaDB 10.2
    MariaDB 10.2
    MariaDB 10.2
    INSERT
    UPDATE
    DELETE
    REPLACE
    REPLACE
    error code
    UPDATE
    DELETE
    INSERT
    AUTO_INCREMENT
    INSERT
    UPDATE
    SQL_MODE
    SELECT
    SHOW
    DESCRIBE
    EXPLAIN
    max_allowed_packet
    TEXT
    BLOB