Table of Contents
This chapter describes the APIs available for MySQL, where to get
them, and how to use them. The C API is the most extensively
covered, because it was developed by the MySQL team, and is the
basis for most of the other APIs. This chapter also covers the
libmysqld library (the embedded server), as well
as some programs that are useful for application developers.
The embedded MySQL server library makes it possible to run a full-featured MySQL server inside a client application. The main benefits are increased speed and more simple management for embedded applications.
The embedded server library is based on the client/server version of MySQL, which is written in C/C++. Consequently, the embedded server also is written in C/C++. There is no embedded server available in other languages.
The API is identical for the embedded MySQL version and the client/server version. To change an old threaded application to use the embedded library, you normally only have to add calls to the following functions:
| Function | When to Call |
mysql_library_init() | Should be called before any other MySQL function is called, preferably
early in the main() function. |
mysql_library_end() | Should be called before your program exits. |
mysql_thread_init() | Should be called in each thread you create that accesses MySQL. |
mysql_thread_end() | Should be called before calling pthread_exit() |
Then you must link your code with
libmysqld.a instead of
libmysqlclient.a. To ensure binary
compatibility between your application and the server library,
be sure to compile your application against headers for the same
series of MySQL that was used to compile the server library. For
example, if libmysqld was compiled against
MySQL 4.1 headers, do not compile your application against MySQL
5.1 headers, or vice versa.
The
mysql_library_
functions are also included in
xxx()libmysqlclient.a to allow you to change
between the embedded and the client/server version by just
linking your application with the right library. See
Section 17.2.3.38, “mysql_library_init()”.
One difference between the embedded server and the standalone
server is that for the embedded server, authentication for
connections is disabled by default. To use authentication for
the embedded server, specify the
--with-embedded-privilege-control option when
you invoke configure to configure your MySQL
distribution. This option is available as of MySQL 4.1.3.
To get a libmysqld library you should
configure MySQL with the --with-embedded-server
option. See Section 2.9.2, “Typical configure Options”.
When you link your program with libmysqld,
you must also include the system-specific
pthread libraries and some libraries that the
MySQL server uses. You can get the full list of libraries by
executing mysql_config --libmysqld-libs.
The correct flags for compiling and linking a threaded program must be used, even if you do not directly call any thread functions in your code.
To compile a C program to include the necessary files to embed
the MySQL server library into a compiled version of a program,
use the GNU C compiler (gcc). The compiler
will need to know where to find various files and need
instructions on how to compile the program. The following
example shows how a program could be compiled from the command
line:
gcc mysql_test.c -o mysql_test -lz \ `/usr/local/mysql/bin/mysql_config --include --libmysqld-libs`
Immediately following the gcc command is the
name of the uncompiled C program file. After it, the
-o option is given to indicate that the file
name that follows is the name that the compiler is to give to
the output file, the compiled program. The next line of code
tells the compiler to obtain the location of the include files
and libraries and other settings for the system on which it's
compiled. Because of a problem with
mysql_config, the option -lz
(for compression) is added here. The
mysql_config piece is contained in backticks,
not single quotes.
The embedded server has the following limitations:
No support for ISAM tables. (This is done
mainly to make the library smaller.)
No user-defined functions (UDFs).
No stack trace on core dump.
No internal RAID support. (This is not normally needed as most current operating systems support big files.)
You cannot set this up as a master or a slave (no replication).
Very large result sets may be unusable on low memory systems.
You cannot connect to an embedded server from an outside process with sockets or TCP/IP. However, you can connect to an intermediate application, which in turn can connect to an embedded server on the behalf of a remote client or outside process.
Some of these limitations can be changed by editing the
mysql_embed.h include file and recompiling
MySQL.
Any options that may be given with the mysqld
server daemon, may be used with an embedded server library.
Server options may be given in an array as an argument to the
mysql_library_init(), which initializes the
server. They also may be given in an option file like
my.cnf. To specify an option file for a C
program, use the --defaults-file option as one
of the elements of the second argument of the
mysql_library_init() function. See
Section 17.2.3.38, “mysql_library_init()”, for more information on
the mysql_library_init() function.
Using option files can make it easier to switch between a
client/server application and one where MySQL is embedded. Put
common options under the [server] group.
These are read by both MySQL versions. Client/server-specific
options should go under the [mysqld] section.
Put options specific to the embedded MySQL server library in the
[embedded] section. Options specific to
applications go under section labeled
[ApplicationName_SERVER]. See
Section 4.3.2, “Using Option Files”.
These two example programs should work without any changes on a Linux or FreeBSD system. For other operating systems, minor changes are needed, mostly with file paths. These examples are designed to give enough details for you to understand the problem, without the clutter that is a necessary part of a real application. The first example is very straightforward. The second example is a little more advanced with some error checking. The first is followed by a command-line entry for compiling the program. The second is followed by a GNUmake file that may be used for compiling instead.
Example 1
test1_libmysqld.c
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "mysql.h"
MYSQL *mysql;
MYSQL_RES *results;
MYSQL_ROW record;
static char *server_options[] = { "mysql_test", "--defaults-file=my.cnf", NULL };
int num_elements = (sizeof(server_options) / sizeof(char *)) - 1;
static char *server_groups[] = { "libmysqld_server", "libmysqld_client", NULL };
int main(void)
{
mysql_library_init(num_elements, server_options, server_groups);
mysql = mysql_init(NULL);
mysql_options(mysql, MYSQL_READ_DEFAULT_GROUP, "libmysqld_client");
mysql_options(mysql, MYSQL_OPT_USE_EMBEDDED_CONNECTION, NULL);
mysql_real_connect(mysql, NULL,NULL,NULL, "database1", 0,NULL,0);
mysql_query(mysql, "SELECT column1, column2 FROM table1");
results = mysql_store_result(mysql);
while((record = mysql_fetch_row(results))) {
printf("%s - %s \n", record[0], record[1]);
}
mysql_free_result(results);
mysql_close(mysql);
mysql_library_end();
return 0;
}
Here is the command line for compiling the above program:
gcc test1_libmysqld.c -o test1_libmysqld -lz \ `/usr/local/mysql/bin/mysql_config --include --libmysqld-libs`
Example 2
To try out the example, create a
test2_libmysqld directory at the same level
as the MySQL source directory. Save the
test2_libmysqld.c source and the
GNUmakefile in the directory, and run GNU
make from inside the
test2_libmysqld directory.
test2_libmysqld.c
/*
* A simple example client, using the embedded MySQL server library
*/
#include <mysql.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
MYSQL *db_connect(const char *dbname);
void db_disconnect(MYSQL *db);
void db_do_query(MYSQL *db, const char *query);
const char *server_groups[] = {
"test2_libmysqld_SERVER", "embedded", "server", NULL
};
int
main(int argc, char **argv)
{
MYSQL *one, *two;
/* mysql_library_init() must be called before any other mysql
* functions.
*
* You can use mysql_library_init(0, NULL, NULL), and it
* initializes the server using groups = {
* "server", "embedded", NULL
* }.
*
* In your $HOME/.my.cnf file, you probably want to put:
[test2_libmysqld_SERVER]
language = /path/to/source/of/mysql/sql/share/english
* You could, of course, modify argc and argv before passing
* them to this function. Or you could create new ones in any
* way you like. But all of the arguments in argv (except for
* argv[0], which is the program name) should be valid options
* for the MySQL server.
*
* If you link this client against the normal mysqlclient
* library, this function is just a stub that does nothing.
*/
mysql_library_init(argc, argv, (char **)server_groups);
one = db_connect("test");
two = db_connect(NULL);
db_do_query(one, "SHOW TABLE STATUS");
db_do_query(two, "SHOW DATABASES");
mysql_close(two);
mysql_close(one);
/* This must be called after all other mysql functions */
mysql_library_end();
exit(EXIT_SUCCESS);
}
static void
die(MYSQL *db, char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
(void)putc('\n', stderr);
if (db)
db_disconnect(db);
exit(EXIT_FAILURE);
}
MYSQL *
db_connect(const char *dbname)
{
MYSQL *db = mysql_init(NULL);
if (!db)
die(db, "mysql_init failed: no memory");
/*
* Notice that the client and server use separate group names.
* This is critical, because the server does not accept the
* client's options, and vice versa.
*/
mysql_options(db, MYSQL_READ_DEFAULT_GROUP, "test2_libmysqld_CLIENT");
if (!mysql_real_connect(db, NULL, NULL, NULL, dbname, 0, NULL, 0))
die(db, "mysql_real_connect failed: %s", mysql_error(db));
return db;
}
void
db_disconnect(MYSQL *db)
{
mysql_close(db);
}
void
db_do_query(MYSQL *db, const char *query)
{
if (mysql_query(db, query) != 0)
goto err;
if (mysql_field_count(db) > 0)
{
MYSQL_RES *res;
MYSQL_ROW row, end_row;
int num_fields;
if (!(res = mysql_store_result(db)))
goto err;
num_fields = mysql_num_fields(res);
while ((row = mysql_fetch_row(res)))
{
(void)fputs(">> ", stdout);
for (end_row = row + num_fields; row < end_row; ++row)
(void)printf("%s\t", row ? (char*)*row : "NULL");
(void)fputc('\n', stdout);
}
(void)fputc('\n', stdout);
mysql_free_result(res);
}
else
(void)printf("Affected rows: %lld\n", mysql_affected_rows(db));
return;
err:
die(db, "db_do_query failed: %s [%s]", mysql_error(db), query);
}
GNUmakefile
# This assumes the MySQL software is installed in /usr/local/mysql
inc := /usr/local/mysql/include/mysql
lib := /usr/local/mysql/lib
# If you have not installed the MySQL software yet, try this instead
#inc := $(HOME)/mysql-4.0/include
#lib := $(HOME)/mysql-4.0/libmysqld
CC := gcc
CPPFLAGS := -I$(inc) -D_THREAD_SAFE -D_REENTRANT
CFLAGS := -g -W -Wall
LDFLAGS := -static
# You can change -lmysqld to -lmysqlclient to use the
# client/server library
LDLIBS = -L$(lib) -lmysqld -lz -lm -lcrypt
ifneq (,$(shell grep FreeBSD /COPYRIGHT 2>/dev/null))
# FreeBSD
LDFLAGS += -pthread
else
# Assume Linux
LDLIBS += -lpthread
endif
# This works for simple one-file test programs
sources := $(wildcard *.c)
objects := $(patsubst %c,%o,$(sources))
targets := $(basename $(sources))
all: $(targets)
clean:
rm -f $(targets) $(objects) *.core
We encourage everyone to promote free software by releasing code under the GPL or a compatible license. For those who are not able to do this, another option is to purchase a commercial license for the MySQL code from MySQL AB. For details, please see http://www.mysql.com/company/legal/licensing/.
The C API code is distributed with MySQL. It is included in the
mysqlclient library and allows C programs to
access a database.
Many of the clients in the MySQL source distribution are written in
C. If you are looking for examples that demonstrate how to use the C
API, take a look at these clients. You can find these in the
clients directory in the MySQL source
distribution.
Most of the other client APIs (all except Connector/J and
Connector/NET) use the mysqlclient library to
communicate with the MySQL server. This means that, for example, you
can take advantage of many of the same environment variables that
are used by other client programs, because they are referenced from
the library. See Chapter 8, Client and Utility Programs, for a
list of these variables.
The client has a maximum communication buffer size. The size of the buffer that is allocated initially (16KB) is automatically increased up to the maximum size (the maximum is 16MB). Because buffer sizes are increased only as demand warrants, simply increasing the default maximum limit does not in itself cause more resources to be used. This size check is mostly a check for erroneous statements and communication packets.
The communication buffer must be large enough to contain a single
SQL statement (for client-to-server traffic) and one row of returned
data (for server-to-client traffic). Each thread's communication
buffer is dynamically enlarged to handle any query or row up to the
maximum limit. For example, if you have BLOB
values that contain up to 16MB of data, you must have a
communication buffer limit of at least 16MB (in both server and
client). The client's default maximum is 16MB, but the default
maximum in the server is 1MB. You can increase this by changing the
value of the max_allowed_packet parameter when
the server is started. See Section 7.5.2, “Tuning Server Parameters”.
The MySQL server shrinks each communication buffer to
net_buffer_length bytes after each query. For
clients, the size of the buffer associated with a connection is not
decreased until the connection is closed, at which time client
memory is reclaimed.
For programming with threads, see Section 17.2.16, “How to Make a Threaded Client”. For creating a standalone application which includes the "server" and "client" in the same program (and does not communicate with an external MySQL server), see Section 17.1, “libmysqld, the Embedded MySQL Server Library”.
This structure represents a handle to one database connection.
It is used for almost all MySQL functions. You should not try
to make a copy of a MYSQL structure. There
is no guarantee that such a copy will be usable.
This structure represents the result of a query that returns
rows (SELECT, SHOW,
DESCRIBE, EXPLAIN). The
information returned from a query is called the
result set in the remainder of this
section.
This is a type-safe representation of one row of data. It is
currently implemented as an array of counted byte strings.
(You cannot treat these as null-terminated strings if field
values may contain binary data, because such values may
contain null bytes internally.) Rows are obtained by calling
mysql_fetch_row().
This structure contains information about a field, such as the
field's name, type, and size. Its members are described in
more detail here. You may obtain the
MYSQL_FIELD structures for each field by
calling mysql_fetch_field() repeatedly.
Field values are not part of this structure; they are
contained in a MYSQL_ROW structure.
This is a type-safe representation of an offset into a MySQL
field list. (Used by mysql_field_seek().)
Offsets are field numbers within a row, beginning at zero.
The type used for the number of rows and for
mysql_affected_rows(),
mysql_num_rows(), and
mysql_insert_id(). This type provides a
range of 0 to 1.84e19.
On some systems, attempting to print a value of type
my_ulonglong does not work. To print such a
value, convert it to unsigned long and use
a %lu print format. Example:
printf ("Number of rows: %lu\n",
(unsigned long) mysql_num_rows(result));
A boolean type, for values that are true (non-zero) or false (zero).
The MYSQL_FIELD structure contains the members
listed here:
char * name
The name of the field, as a null-terminated string. If the
field was given an alias with an AS clause,
the value of name is the alias.
char * org_name
The name of the field, as a null-terminated string. Aliases are ignored. This member was added in MySQL 4.1.0.
char * table
The name of the table containing this field, if it isn't a
calculated field. For calculated fields, the
table value is an empty string. If the
table was given an alias with an AS clause,
the value of table is the alias.
char * org_table
The name of the table, as a null-terminated string. Aliases are ignored. This member was added in MySQL 4.1.0.
char * db
The name of the database that the field comes from, as a
null-terminated string. If the field is a calculated field,
db is an empty string. This member was
added in MySQL 4.1.0.
char * catalog
The catalog name. This value is always
"def". This member was added in MySQL
4.1.1.
char * def
The default value of this field, as a null-terminated string.
This is set only if you use
mysql_list_fields().
unsigned long length
The width of the field. This corresponds to the display length, in bytes.
unsigned long max_length
The maximum width of the field for the result set (the length
in bytes of the longest field value for the rows actually in
the result set). If you use
mysql_store_result() or
mysql_list_fields(), this contains the
maximum length for the field. If you use
mysql_use_result(), the value of this
variable is zero.
The value of max_length is the length of
the string representation of the values in the result set. For
example, if you retrieve a FLOAT column and
the “widest” value is -12.345,
max_length is 7 (the length of
'-12.345').
If you are using the prepared statements,
max_length is not set by default because
for the binary protocol the lengths of the values depend on
the types of the values in the result set. (See
Section 17.2.5, “C API Prepared Statement Data types”.) If you
want the max_length values anyway, enable
the STMT_ATTR_UPDATE_MAX_LENGTH option with
mysql_stmt_attr_set() and the lengths will
be set when you call
mysql_stmt_store_result(). (See
Section 17.2.7.3, “mysql_stmt_attr_set()”, and
Section 17.2.7.27, “mysql_stmt_store_result()”.)
unsigned int name_length
The length of name. This member was added
in MySQL 4.1.0.
unsigned int org_name_length
The length of org_name. This member was
added in MySQL 4.1.0.
unsigned int table_length
The length of table. This member was added
in MySQL 4.1.0.
unsigned int org_table_length
The length of org_table. This member was
added in MySQL 4.1.0.
unsigned int db_length
The length of db. This member was added in
MySQL 4.1.0.
unsigned int catalog_length
The length of catalog. This member was
added in MySQL 4.1.1.
unsigned int def_length
The length of def. This member was added in
MySQL 4.1.0.
unsigned int flags
Different bit-flags for the field. The
flags value may have zero or more of the
following bits set:
| Flag Value | Flag Description |
NOT_NULL_FLAG | Field can't be NULL |
PRI_KEY_FLAG | Field is part of a primary key |
UNIQUE_KEY_FLAG | Field is part of a unique key |
MULTIPLE_KEY_FLAG | Field is part of a non-unique key |
UNSIGNED_FLAG | Field has the UNSIGNED attribute |
ZEROFILL_FLAG | Field has the ZEROFILL attribute |
BINARY_FLAG | Field has the BINARY attribute |
AUTO_INCREMENT_FLAG | Field has the AUTO_INCREMENT attribute |
ENUM_FLAG | Field is an ENUM (deprecated) |
SET_FLAG | Field is a SET (deprecated) |
BLOB_FLAG | Field is a BLOB or TEXT
(deprecated) |
TIMESTAMP_FLAG | Field is a TIMESTAMP (deprecated) |
Use of the BLOB_FLAG,
ENUM_FLAG, SET_FLAG, and
TIMESTAMP_FLAG flags is deprecated because
they indicate the type of a field rather than an attribute of
its type. It is preferable to test
field->type against
MYSQL_TYPE_BLOB,
MYSQL_TYPE_ENUM,
MYSQL_TYPE_SET, or
MYSQL_TYPE_TIMESTAMP instead.
The following example illustrates a typical use of the
flags value:
if (field->flags & NOT_NULL_FLAG)
printf("Field can't be null\n");
You may use the following convenience macros to determine the
boolean status of the flags value:
| Flag Status | Description |
IS_NOT_NULL(flags) | True if this field is defined as NOT NULL |
IS_PRI_KEY(flags) | True if this field is a primary key |
IS_BLOB(flags) | True if this field is a BLOB or
TEXT (deprecated; test
field->type instead) |
unsigned int decimals
The number of decimals for numeric fields.
unsigned int charsetnr
The character set number for the field. This member was added in MySQL 4.1.0.
enum enum_field_types type
The type of the field. The type value may
be one of the MYSQL_TYPE_ symbols shown in
the following table. Before MySQL 4.1, the symbol names begin
with FIELD_TYPE_ rather than
MYSQL_TYPE_. The older types still are
recognized for backward compatibility.
| Type Value | Type Description |
MYSQL_TYPE_TINY | TINYINT field |
MYSQL_TYPE_SHORT | SMALLINT field |
MYSQL_TYPE_LONG | INTEGER field |
MYSQL_TYPE_INT24 | MEDIUMINT field |
MYSQL_TYPE_LONGLONG | BIGINT field |
MYSQL_TYPE_DECIMAL | DECIMAL or NUMERIC field |
MYSQL_TYPE_FLOAT | FLOAT field |
MYSQL_TYPE_DOUBLE | DOUBLE or REAL field |
MYSQL_TYPE_TIMESTAMP | TIMESTAMP field |
MYSQL_TYPE_DATE | DATE field |
MYSQL_TYPE_TIME | TIME field |
MYSQL_TYPE_DATETIME | DATETIME field |
MYSQL_TYPE_YEAR | YEAR field |
MYSQL_TYPE_STRING | CHAR or BINARY field |
MYSQL_TYPE_VAR_STRING | VARCHAR or VARBINARY field |
MYSQL_TYPE_BLOB | BLOB or TEXT field (use
max_length to determine the maximum
length) |
MYSQL_TYPE_SET | SET field |
MYSQL_TYPE_ENUM | ENUM field |
MYSQL_TYPE_GEOMETRY | Spatial field (MySQL 4.1.0 and up) |
MYSQL_TYPE_NULL | NULL-type field |
You can use the IS_NUM() macro to test
whether a field has a numeric type. Pass the
type value to IS_NUM()
and it evaluates to TRUE if the field is numeric:
if (IS_NUM(field->type))
printf("Field is numeric\n");
To distinguish between binary and non-binary data for string
data types, check whether the charsetnr
value is 63. If so, the character set is
binary, which indicates binary rather than
non-binary data. This is how to distinguish between
BINARY and CHAR,
VARBINARY and VARCHAR,
and BLOB and TEXT.
The functions available in the C API are summarized here and described in greater detail in a later section. See Section 17.2.3, “C API Function Descriptions”.
| Function | Description |
| my_init() | Initialize global variables, and thread handler in thread-safe programs. |
| mysql_affected_rows() | Returns the number of rows changed/deleted/inserted by the last
UPDATE, DELETE, or
INSERT query. |
| mysql_autocommit() | Toggles autocommit mode on/off. |
| mysql_change_user() | Changes user and database on an open connection. |
| mysql_close() | Closes a server connection. |
| mysql_commit() | Commits the transaction. |
| mysql_connect() | Connects to a MySQL server. This function is deprecated; use
mysql_real_connect() instead. |
| mysql_create_db() | Creates a database. This function is deprecated; use the SQL statement
CREATE DATABASE instead. |
| mysql_data_seek() | Seeks to an arbitrary row number in a query result set. |
| mysql_debug() | Does a DBUG_PUSH with the given string. |
| mysql_drop_db() | Drops a database. This function is deprecated; use the SQL statement
DROP DATABASE instead. |
| mysql_dump_debug_info() | Makes the server write debug information to the log. |
| mysql_eof() | Determines whether the last row of a result set has been read. This
function is deprecated; mysql_errno()
or mysql_error() may be used instead. |
| mysql_errno() | Returns the error number for the most recently invoked MySQL function. |
| mysql_error() | Returns the error message for the most recently invoked MySQL function. |
| mysql_escape_string() | Escapes special characters in a string for use in an SQL statement. |
| mysql_fetch_field() | Returns the type of the next table field. |
| mysql_fetch_field_direct() | Returns the type of a table field, given a field number. |
| mysql_fetch_fields() | Returns an array of all field structures. |
| mysql_fetch_lengths() | Returns the lengths of all columns in the current row. |
| mysql_fetch_row() | Fetches the next row from the result set. |
| mysql_field_seek() | Puts the column cursor on a specified column. |
| mysql_field_count() | Returns the number of result columns for the most recent statement. |
| mysql_field_tell() | Returns the position of the field cursor used for the last
mysql_fetch_field(). |
| mysql_free_result() | Frees memory used by a result set. |
| mysql_get_client_info() | Returns client version information as a string. |
| mysql_get_client_version() | Returns client version information as an integer. |
| mysql_get_host_info() | Returns a string describing the connection. |
| mysql_get_server_version() | Returns version number of server as an integer (new in 4.1). |
| mysql_get_proto_info() | Returns the protocol version used by the connection. |
| mysql_get_server_info() | Returns the server version number. |
| mysql_info() | Returns information about the most recently executed query. |
| mysql_init() | Gets or initializes a MYSQL structure. |
| mysql_insert_id() | Returns the ID generated for an AUTO_INCREMENT column
by the previous query. |
| mysql_kill() | Kills a given thread. |
| mysql_library_end() | Finalize the MySQL C API library. |
| mysql_library_init() | Initialize the MySQL C API library. |
| mysql_list_dbs() | Returns database names matching a simple regular expression. |
| mysql_list_fields() | Returns field names matching a simple regular expression. |
| mysql_list_processes() | Returns a list of the current server threads. |
| mysql_list_tables() | Returns table names matching a simple regular expression. |
| mysql_more_results() | Checks whether any more results exist. |
| mysql_next_result() | Returns/initiates the next result in multiple-statement executions. |
| mysql_num_fields() | Returns the number of columns in a result set. |
| mysql_num_rows() | Returns the number of rows in a result set. |
| mysql_options() | Sets connect options for mysql_connect(). |
| mysql_ping() | Checks whether the connection to the server is working, reconnecting as necessary. |
| mysql_query() | Executes an SQL query specified as a null-terminated string. |
| mysql_real_connect() | Connects to a MySQL server. |
| mysql_real_escape_string() | Escapes special characters in a string for use in an SQL statement, taking into account the current character set of the connection. |
| mysql_real_query() | Executes an SQL query specified as a counted string. |
| mysql_refresh() | Flush or reset tables and caches. |
| mysql_reload() | Tells the server to reload the grant tables. |
| mysql_rollback() | Rolls back the transaction. |
| mysql_row_seek() | Seeks to a row offset in a result set, using value returned from
mysql_row_tell(). |
| mysql_row_tell() | Returns the row cursor position. |
| mysql_select_db() | Selects a database. |
| mysql_server_end() | Finalize the MySQL C API library. |
| mysql_server_init() | Initialize the MySQL C API library. |
| mysql_set_local_infile_default() | Set the LOAD DATA LOCAL INFILE handler callbacks to
their default values. |
| mysql_set_local_infile_handler() | Install application-specific LOAD DATA LOCAL INFILE
handler callbacks. |
| mysql_set_server_option() | Sets an option for the connection (like
multi-statements). |
| mysql_sqlstate() | Returns the SQLSTATE error code for the last error. |
| mysql_shutdown() | Shuts down the database server. |
| mysql_stat() | Returns the server status as a string. |
| mysql_store_result() | Retrieves a complete result set to the client. |
| mysql_thread_end() | Finalize thread handler. |
| mysql_thread_id() | Returns the current thread ID. |
| mysql_thread_init() | Initialize thread handler. |
| mysql_thread_safe() | Returns 1 if the clients are compiled as thread-safe. |
| mysql_use_result() | Initiates a row-by-row result set retrieval. |
| mysql_warning_count() | Returns the warning count for the previous SQL statement. |
Application programs should use this general outline for interacting with MySQL:
Initialize the MySQL library by calling
mysql_library_init(). This function exists
in both the mysqlclient C client library
and the mysqld embedded server library, so
it is used whether you build a regular client program by
linking with the -libmysqlclient flag, or an
embedded server application by linking with the
-libmysqld flag.
Initialize a connection handler by calling
mysql_init() and connect to the server by
calling mysql_real_connect().
Issue SQL statements and process their results. (The following discussion provides more information about how to do this.)
Close the connection to the MySQL server by calling
mysql_close().
End use of the MySQL library by calling
mysql_library_end().
The purpose of calling mysql_library_init() and
mysql_library_end() is to provide proper
initialization and finalization of the MySQL library. For
applications that are linked with the client library, they provide
improved memory management. If you don't call
mysql_library_end(), a block of memory remains
allocated. (This does not increase the amount of memory used by
the application, but some memory leak detectors will complain
about it.) For applications that are linked with the embedded
server, these calls start and stop the server.
mysql_library_init() and
mysql_library_end() are available as of MySQL
4.1.10. For older versions of MySQL, you can call
mysql_server_init() and
mysql_server_end() instead.
In a non-multi-threaded environment, the call to
mysql_library_init() may be omitted, because
mysql_init() will invoke it automatically as
necessary. However, mysql_library_init() is not
thread-safe in a multi-threaded environment, and thus neither is
mysql_init(), which calls
mysql_library_init(). You must either call
mysql_library_init() prior to spawning any
threads, or else use a mutex to protect the call, whether you
invoke mysql_library_init() or indirectly via
mysql_init(). This should be done prior to any
other client library call.
To connect to the server, call mysql_init() to
initialize a connection handler, then call
mysql_real_connect() with that handler (along
with other information such as the hostname, username, and
password). Upon connection,
mysql_real_connect() sets the
reconnect flag (part of the
MYSQL structure) to a value of
1. A value of 1 for this
flag indicates that if a statement cannot be performed because of
a lost connection, to try reconnecting to the server before giving
up. When you are done with the connection, call
mysql_close() to terminate it.
While a connection is active, the client may send SQL statements
to the server using mysql_query() or
mysql_real_query(). The difference between the
two is that mysql_query() expects the query to
be specified as a null-terminated string whereas
mysql_real_query() expects a counted string. If
the string contains binary data (which may include null bytes),
you must use mysql_real_query().
For each non-SELECT query (for example,
INSERT, UPDATE,
DELETE), you can find out how many rows were
changed (affected) by calling
mysql_affected_rows().
For SELECT queries, you retrieve the selected
rows as a result set. (Note that some statements are
SELECT-like in that they return rows. These
include SHOW, DESCRIBE, and
EXPLAIN. They should be treated the same way as
SELECT statements.)
There are two ways for a client to process result sets. One way is
to retrieve the entire result set all at once by calling
mysql_store_result(). This function acquires
from the server all the rows returned by the query and stores them
in the client. The second way is for the client to initiate a
row-by-row result set retrieval by calling
mysql_use_result(). This function initializes
the retrieval, but does not actually get any rows from the server.
In both cases, you access rows by calling
mysql_fetch_row(). With
mysql_store_result(),
mysql_fetch_row() accesses rows that have
previously been fetched from the server. With
mysql_use_result(),
mysql_fetch_row() actually retrieves the row
from the server. Information about the size of the data in each
row is available by calling
mysql_fetch_lengths().
After you are done with a result set, call
mysql_free_result() to free the memory used for
it.
The two retrieval mechanisms are complementary. Client programs
should choose the approach that is most appropriate for their
requirements. In practice, clients tend to use
mysql_store_result() more commonly.
An advantage of mysql_store_result() is that
because the rows have all been fetched to the client, you not only
can access rows sequentially, you can move back and forth in the
result set using mysql_data_seek() or
mysql_row_seek() to change the current row
position within the result set. You can also find out how many
rows there are by calling mysql_num_rows(). On
the other hand, the memory requirements for
mysql_store_result() may be very high for large
result sets and you are more likely to encounter out-of-memory
conditions.
An advantage of mysql_use_result() is that the
client requires less memory for the result set because it
maintains only one row at a time (and because there is less
allocation overhead, mysql_use_result() can be
faster). Disadvantages are that you must process each row quickly
to avoid tying up the server, you don't have random access to rows
within the result set (you can only access rows sequentially), and
you don't know how many rows are in the result set until you have
retrieved them all. Furthermore, you
must retrieve all the rows even
if you determine in mid-retrieval that you've found the
information you were looking for.
The API makes it possible for clients to respond appropriately to
statements (retrieving rows only as necessary) without knowing
whether the statement is a SELECT. You can do
this by calling mysql_store_result() after each
mysql_query() (or
mysql_real_query()). If the result set call
succeeds, the statement was a SELECT and you
can read the rows. If the result set call fails, call
mysql_field_count() to determine whether a
result was actually to be expected. If
mysql_field_count() returns zero, the statement
returned no data (indicating that it was an
INSERT, UPDATE,
DELETE, and so forth), and was not expected to
return rows. If mysql_field_count() is
non-zero, the statement should have returned rows, but didn't.
This indicates that the statement was a SELECT
that failed. See the description for
mysql_field_count() for an example of how this
can be done.
Both mysql_store_result() and
mysql_use_result() allow you to obtain
information about the fields that make up the result set (the
number of fields, their names and types, and so forth). You can
access field information sequentially within the row by calling
mysql_fetch_field() repeatedly, or by field
number within the row by calling
mysql_fetch_field_direct(). The current field
cursor position may be changed by calling
mysql_field_seek(). Setting the field cursor
affects subsequent calls to
mysql_fetch_field(). You can also get
information for fields all at once by calling
mysql_fetch_fields().
For detecting and reporting errors, MySQL provides access to error
information by means of the mysql_errno() and
mysql_error() functions. These return the error
code or error message for the most recently invoked function that
can succeed or fail, allowing you to determine when an error
occurred and what it was.
mysql_affected_rows()mysql_autocommit()mysql_change_user()mysql_character_set_name()mysql_close()mysql_commit()mysql_connect()mysql_create_db()mysql_data_seek()mysql_debug()mysql_drop_db()mysql_dump_debug_info()mysql_eof()mysql_errno()mysql_error()mysql_escape_string()mysql_fetch_field()mysql_fetch_field_direct()mysql_fetch_fields()mysql_fetch_lengths()mysql_fetch_row()mysql_field_count()mysql_field_seek()mysql_field_tell()mysql_free_result()mysql_get_client_info()mysql_get_client_version()mysql_get_host_info()mysql_get_proto_info()mysql_get_server_info()mysql_get_server_version()mysql_hex_string()mysql_info()mysql_init()mysql_insert_id()mysql_kill()mysql_library_end()mysql_library_init()mysql_list_dbs()mysql_list_fields()mysql_list_processes()mysql_list_tables()mysql_more_results()mysql_next_result()mysql_num_fields()mysql_num_rows()mysql_options()mysql_ping()mysql_query()mysql_real_connect()mysql_real_escape_string()mysql_real_query()mysql_refresh()mysql_reload()mysql_rollback()mysql_row_seek()mysql_row_tell()mysql_select_db()mysql_set_character_set()mysql_set_local_infile_default()mysql_set_local_infile_handler()mysql_set_server_option()mysql_shutdown()mysql_sqlstate()mysql_ssl_set()mysql_stat()mysql_store_result()mysql_thread_id()mysql_use_result()mysql_warning_count()
In the descriptions here, a parameter or return value of
NULL means NULL in the sense
of the C programming language, not a MySQL NULL
value.
Functions that return a value generally return a pointer or an
integer. Unless specified otherwise, functions returning a pointer
return a non-NULL value to indicate success or
a NULL value to indicate an error, and
functions returning an integer return zero to indicate success or
non-zero to indicate an error. Note that “non-zero”
means just that. Unless the function description says otherwise,
do not test against a value other than zero:
if (result) /* correct */
... error ...
if (result < 0) /* incorrect */
... error ...
if (result == -1) /* incorrect */
... error ...
When a function returns an error, the
Errors subsection of the function
description lists the possible types of errors. You can find out
which of these occurred by calling
mysql_errno(). A string representation of the
error may be obtained by calling mysql_error().
my_ulonglong mysql_affected_rows(MYSQL
*mysql)
Description
After executing a statement with
mysql_query() or
mysql_real_query(), returns the number of
rows changed (for) UPDATE), deleted (for
DELETE, or inserted (for
INSERT. For SELECT
statements, mysql_affected_rows() works like
mysql_num_rows().
Return Values
An integer greater than zero indicates the number of rows
affected or retrieved. Zero indicates that no records were
updated for an UPDATE statement, no rows
matched the WHERE clause in the query or that
no query has yet been executed. -1 indicates that the query
returned an error or that, for a SELECT
query, mysql_affected_rows() was called prior
to calling mysql_store_result(). Because
mysql_affected_rows() returns an unsigned
value, you can check for -1 by comparing the return value to
(my_ulonglong)-1 (or to
(my_ulonglong)~0, which is equivalent).
Errors
None.
Example
char *stmt = "UPDATE products SET cost=cost*1.25 WHERE group=10";
mysql_query(&mysql,stmt);
printf("%ld products updated",
(long) mysql_affected_rows(&mysql));
For UPDATE statements, if you specify the
CLIENT_FOUND_ROWS flag when connecting to
mysqld,
mysql_affected_rows() returns the number of
rows matched by the WHERE clause. Otherwise,
the default behavior is to return the number of rows actually
changed.
Note that when you use a REPLACE command,
mysql_affected_rows() returns 2 if the new
row replaced an old row, because in this case, one row was
inserted after the duplicate was deleted.
If you use INSERT ... ON DUPLICATE KEY UPDATE
to insert a row, mysql_affected_rows()
returns 1 if the row is inserted as a new row and 2 if an
existing row is updated.
my_bool mysql_autocommit(MYSQL *mysql, my_bool
mode)
Description
Sets autocommit mode on if mode is 1, off if
mode is 0.
This function was added in MySQL 4.1.0.
Return Values
Zero if successful. Non-zero if an error occurred.
Errors
None.
my_bool mysql_change_user(MYSQL *mysql, const char
*user, const char *password, const char *db)
Description
Changes the user and causes the database specified by
db to become the default (current) database
on the connection specified by mysql. In
subsequent queries, this database is the default for table
references that do not include an explicit database specifier.
This function was introduced in MySQL 3.23.3.
mysql_change_user() fails if the connected
user cannot be authenticated or doesn't have permission to use
the database. In this case, the user and database are not
changed
The db parameter may be set to
NULL if you don't want to have a default
database.
Starting from MySQL 4.0.6, this command resets the state as if
one had done a new connect. (See
Section 17.2.13, “Controlling Automatic Reconnect Behavior”.) It always performs a
ROLLBACK of any active transactions, closes
and drops all temporary tables, and unlocks all locked tables.
Session system variables are reset to the values of the
corresponding global system variables. Prepared statements are
released and HANDLER variables are closed.
Locks acquired with GET_LOCK() are released.
These effects occur even if the user didn't change.
Return Values
Zero for success. Non-zero if an error occurred.
Errors
The same that you can get from
mysql_real_connect().
CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
CR_SERVER_GONE_ERROR
The MySQL server has gone away.
CR_SERVER_LOST
The connection to the server was lost during the query.
CR_UNKNOWN_ERROR
An unknown error occurred.
ER_UNKNOWN_COM_ERROR
The MySQL server doesn't implement this command (probably an old server).
ER_ACCESS_DENIED_ERROR
The user or password was wrong.
ER_BAD_DB_ERROR
The database didn't exist.
ER_DBACCESS_DENIED_ERROR
The user did not have access rights to the database.
ER_WRONG_DB_NAME
The database name was too long.
Example
if (mysql_change_user(&mysql, "user", "password", "new_database"))
{
fprintf(stderr, "Failed to change user. Error: %s\n",
mysql_error(&mysql));
}
const char *mysql_character_set_name(MYSQL
*mysql)
Description
Returns the default character set for the current connection.
Return Values
The default character set
Errors
None.
void mysql_close(MYSQL *mysql)
Description
Closes a previously opened connection.
mysql_close() also deallocates the connection
handle pointed to by mysql if the handle was
allocated automatically by mysql_init() or
mysql_connect().
Return Values
None.
Errors
None.
my_bool mysql_commit(MYSQL *mysql)
Description
Commits the current transaction.
This function was added in MySQL 4.1.0.
Return Values
Zero if successful. Non-zero if an error occurred.
Errors
None.
MYSQL *mysql_connect(MYSQL *mysql, const char *host,
const char *user, const char *passwd)
Description
This function is deprecated. It is preferable to use
mysql_real_connect() instead.
mysql_connect() attempts to establish a
connection to a MySQL database engine running on
host. mysql_connect() must
complete successfully before you can execute any of the other
API functions, with the exception of
mysql_get_client_info().
The meanings of the parameters are the same as for the
corresponding parameters for
mysql_real_connect() with the difference that
the connection parameter may be NULL. In this
case, the C API allocates memory for the connection structure
automatically and frees it when you call
mysql_close(). The disadvantage of this
approach is that you can't retrieve an error message if the
connection fails. (To get error information from
mysql_errno() or
mysql_error(), you must provide a valid
MYSQL pointer.)
Return Values
Same as for mysql_real_connect().
Errors
Same as for mysql_real_connect().
int mysql_create_db(MYSQL *mysql, const char
*db)
Description
Creates the database named by the db
parameter.
This function is deprecated. It is preferable to use
mysql_query() to issue an SQL CREATE
DATABASE statement instead.
Return Values
Zero if the database was created successfully. Non-zero if an error occurred.
Errors
CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
CR_SERVER_GONE_ERROR
The MySQL server has gone away.
CR_SERVER_LOST
The connection to the server was lost during the query.
CR_UNKNOWN_ERROR
An unknown error occurred.
Example
if(mysql_create_db(&mysql, "my_database"))
{
fprintf(stderr, "Failed to create new database. Error: %s\n",
mysql_error(&mysql));
}
void mysql_data_seek(MYSQL_RES *result, my_ulonglong
offset)
Description
Seeks to an arbitrary row in a query result set. The
offset value is a row number and should be in
the range from 0 to
mysql_num_rows(result)-1.
This function requires that the result set structure contains
the entire result of the query, so
mysql_data_seek() may be used only in
conjunction with mysql_store_result(), not
with mysql_use_result().
Return Values
None.
Errors
None.
void mysql_debug(const char *debug)
Description
Does a DBUG_PUSH with the given string.
mysql_debug() uses the Fred Fish debug
library. To use this function, you must compile the client
library to support debugging. See
MySQL
Internals: Porting.
Return Values
None.
Errors
None.
Example
The call shown here causes the client library to generate a
trace file in /tmp/client.trace on the
client machine:
mysql_debug("d:t:O,/tmp/client.trace");
int mysql_drop_db(MYSQL *mysql, const char
*db)
Description
Drops the database named by the db parameter.
This function is deprecated. It is preferable to use
mysql_query() to issue an SQL DROP
DATABASE statement instead.
Return Values
Zero if the database was dropped successfully. Non-zero if an error occurred.
Errors
CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
CR_SERVER_GONE_ERROR
The MySQL server has gone away.
CR_SERVER_LOST
The connection to the server was lost during the query.
CR_UNKNOWN_ERROR
An unknown error occurred.
Example
if(mysql_drop_db(&mysql, "my_database"))
fprintf(stderr, "Failed to drop the database: Error: %s\n",
mysql_error(&mysql));
int mysql_dump_debug_info(MYSQL *mysql)
Description
Instructs the server to write some debug information to the log.
For this to work, the connected user must have the
SUPER privilege.
Return Values
Zero if the command was successful. Non-zero if an error occurred.
Errors
CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
CR_SERVER_GONE_ERROR
The MySQL server has gone away.
CR_SERVER_LOST
The connection to the server was lost during the query.
CR_UNKNOWN_ERROR
An unknown error occurred.
my_bool mysql_eof(MYSQL_RES *result)
Description
This function is deprecated. mysql_errno() or
mysql_error() may be used instead.
mysql_eof() determines whether the last row
of a result set has been read.
If you acquire a result set from a successful call to
mysql_store_result(), the client receives the
entire set in one operation. In this case, a
NULL return from
mysql_fetch_row() always means the end of the
result set has been reached and it is unnecessary to call
mysql_eof(). When used with
mysql_store_result(),
mysql_eof() always returns true.
On the other hand, if you use
mysql_use_result() to initiate a result set
retrieval, the rows of the set are obtained from the server one
by one as you call mysql_fetch_row()
repeatedly. Because an error may occur on the connection during
this process, a NULL return value from
mysql_fetch_row() does not necessarily mean
the end of the result set was reached normally. In this case,
you can use mysql_eof() to determine what
happened. mysql_eof() returns a non-zero
value if the end of the result set was reached and zero if an
error occurred.
Historically, mysql_eof() predates the
standard MySQL error functions mysql_errno()
and mysql_error(). Because those error
functions provide the same information, their use is preferred
over mysql_eof(), which is deprecated. (In
fact, they provide more information, because
mysql_eof() returns only a boolean value
whereas the error functions indicate a reason for the error when
one occurs.)
Return Values
Zero if no error occurred. Non-zero if the end of the result set has been reached.
Errors
None.
Example
The following example shows how you might use
mysql_eof():
mysql_query(&mysql,"SELECT * FROM some_table");
result = mysql_use_result(&mysql);
while((row = mysql_fetch_row(result)))
{
// do something with data
}
if(!mysql_eof(result)) // mysql_fetch_row() failed due to an error
{
fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
}
However, you can achieve the same effect with the standard MySQL error functions:
mysql_query(&mysql,"SELECT * FROM some_table");
result = mysql_use_result(&mysql);
while((row = mysql_fetch_row(result)))
{
// do something with data
}
if(mysql_errno(&mysql)) // mysql_fetch_row() failed due to an error
{
fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
}
unsigned int mysql_errno(MYSQL *mysql)
Description
For the connection specified by mysql,
mysql_errno() returns the error code for the
most recently invoked API function that can succeed or fail. A
return value of zero means that no error occurred. Client error
message numbers are listed in the MySQL
errmsg.h header file. Server error message
numbers are listed in mysqld_error.h.
Errors also are listed at Appendix A, Errors, Error Codes, and Common Problems.
Note that some functions like
mysql_fetch_row() don't set
mysql_errno() if they succeed.
A rule of thumb is that all functions that have to ask the
server for information reset mysql_errno() if
they succeed.
MySQL-specific error numbers returned by
mysql_errno() differ from SQLSTATE values
returned by mysql_sqlstate(). For example,
the mysql client program displays errors
using the following format, where 1146 is the
mysql_errno() value and
'42S02' is the corresponding
mysql_sqlstate() value:
shell> SELECT * FROM no_such_table;
ERROR 1146 (42S02): Table 'test.no_such_table' doesn't exist
Return Values
An error code value for the last
mysql_ call,
if it failed. zero means no error occurred.
xxx()
Errors
None.
const char *mysql_error(MYSQL *mysql)
Description
For the connection specified by mysql,
mysql_error() returns a null-terminated
string containing the error message for the most recently
invoked API function that failed. If a function didn't fail, the
return value of mysql_error() may be the
previous error or an empty string to indicate no error.
A rule of thumb is that all functions that have to ask the
server for information reset mysql_error() if
they succeed.
For functions that reset mysql_error(), the
following two tests are equivalent:
if(*mysql_error(&mysql))
{
// an error occurred
}
if(mysql_error(&mysql)[0])
{
// an error occurred
}
The language of the client error messages may be changed by recompiling the MySQL client library. Currently, you can choose error messages in several different languages. See Section 5.10.2, “Setting the Error Message Language”.
Return Values
A null-terminated character string that describes the error. An empty string if no error occurred.
Errors
None.
You should use mysql_real_escape_string()
instead!
This function is identical to
mysql_real_escape_string() except that
mysql_real_escape_string() takes a connection
handler as its first argument and escapes the string according
to the current character set.
mysql_escape_string() does not take a
connection argument and does not respect the current character
set.
MYSQL_FIELD *mysql_fetch_field(MYSQL_RES
*result)
Description
Returns the definition of one column of a result set as a
MYSQL_FIELD structure. Call this function
repeatedly to retrieve information about all columns in the
result set. mysql_fetch_field() returns
NULL when no more fields are left.
mysql_fetch_field() is reset to return
information about the first field each time you execute a new
SELECT query. The field returned by
mysql_fetch_field() is also affected by calls
to mysql_field_seek().
If you've called mysql_query() to perform a
SELECT on a table but have not called
mysql_store_result(), MySQL returns the
default blob length (8KB) if you call
mysql_fetch_field() to ask for the length of
a BLOB field. (The 8KB size is chosen because
MySQL doesn't know the maximum length for the
BLOB. This should be made configurable
sometime.) Once you've retrieved the result set,
field->max_length contains the length of
the largest value for this column in the specific query.
Return Values
The MYSQL_FIELD structure for the current
column. NULL if no columns are left.
Errors
None.
Example
MYSQL_FIELD *field;
while((field = mysql_fetch_field(result)))
{
printf("field name %s\n", field->name);
}
MYSQL_FIELD *mysql_fetch_field_direct(MYSQL_RES
*result, unsigned int fieldnr)
Description
Given a field number fieldnr for a column
within a result set, returns that column's field definition as a
MYSQL_FIELD structure. You may use this
function to retrieve the definition for an arbitrary column. The
value of fieldnr should be in the range from
0 to mysql_num_fields(result)-1.
Return Values
The MYSQL_FIELD structure for the specified
column.
Errors
None.
Example
unsigned int num_fields;
unsigned int i;
MYSQL_FIELD *field;
num_fields = mysql_num_fields(result);
for(i = 0; i < num_fields; i++)
{
field = mysql_fetch_field_direct(result, i);
printf("Field %u is %s\n", i, field->name);
}
MYSQL_FIELD *mysql_fetch_fields(MYSQL_RES
*result)
Description
Returns an array of all MYSQL_FIELD
structures for a result set. Each structure provides the field
definition for one column of the result set.
Return Values
An array of MYSQL_FIELD structures for all
columns of a result set.
Errors
None.
Example
unsigned int num_fields;
unsigned int i;
MYSQL_FIELD *fields;
num_fields = mysql_num_fields(result);
fields = mysql_fetch_fields(result);
for(i = 0; i < num_fields; i++)
{
printf("Field %u is %s\n", i, fields[i].name);
}
unsigned long *mysql_fetch_lengths(MYSQL_RES
*result)
Description
Returns the lengths of the columns of the current row within a
result set. If you plan to copy field values, this length
information is also useful for optimization, because you can
avoid calling strlen(). In addition, if the
result set contains binary data, you
must use this function to
determine the size of the data, because
strlen() returns incorrect results for any
field containing null characters.
The length for empty columns and for columns containing
NULL values is zero. To see how to
distinguish these two cases, see the description for
mysql_fetch_row().
Return Values
An array of unsigned long integers representing the size of each
column (not including any terminating null characters).
NULL if an error occurred.
Errors
mysql_fetch_lengths() is valid only for the
current row of the result set. It returns
NULL if you call it before calling
mysql_fetch_row() or after retrieving all
rows in the result.
Example
MYSQL_ROW row;
unsigned long *lengths;
unsigned int num_fields;
unsigned int i;
row = mysql_fetch_row(result);
if (row)
{
num_fields = mysql_num_fields(result);
lengths = mysql_fetch_lengths(result);
for(i = 0; i < num_fields; i++)
{
printf("Column %u is %lu bytes in length.\n",
i, lengths[i]);
}
}
MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)
Description
Retrieves the next row of a result set. When used after
mysql_store_result(),
mysql_fetch_row() returns
NULL when there are no more rows to retrieve.
When used after mysql_use_result(),
mysql_fetch_row() returns
NULL when there are no more rows to retrieve
or if an error occurred.
The number of values in the row is given by
mysql_num_fields(result). If
row holds the return value from a call to
mysql_fetch_row(), pointers to the values are
accessed as row[0] to
row[mysql_num_fields(result)-1].
NULL values in the row are indicated by
NULL pointers.
The lengths of the field values in the row may be obtained by
calling mysql_fetch_lengths(). Empty fields
and fields containing NULL both have length
0; you can distinguish these by checking the pointer for the
field value. If the pointer is NULL, the
field is NULL; otherwise, the field is empty.
Return Values
A MYSQL_ROW structure for the next row.
NULL if there are no more rows to retrieve or
if an error occurred.
Errors
Note that error is not reset between calls to
mysql_fetch_row()
CR_SERVER_LOST
The connection to the server was lost during the query.