You are on page 1of 288

1 MySQL API

API, MySQL, ,
. C API ,
MySQL API.
1.1 MySQL PHP API
PHP , HTML, ,
, -.
, MySQL.
PHP
- Apache.
web- PHP.
1.1.1 MySQL PHP

Error: "Maximum Execution Time Exceeded". PHP.


php3.ini
.
8 MB 16 MB.
Error: "Fatal error: Call to unsupported or undefined function mysql_connect()
in ..". , PHP MySQL.
MySQL
PHP, PHP MySQL.
PHP .
Error: "undefined reference to `uncompress'". ,

/. , -lz
-lmysqlclient.

1.2 MySQL C++ API


API MySQL Contrib.
1.2.1 Borland C++

MySQL Windows Borland C+


+ 5.02. Windows Microsoft VC++,
Borland C++ .
Borland C++ ,
, VC++. ,
,
libmysql.dll ( VC++) Borland C++.

,
.

MySQL Borland C++,


http://www.mysql.com/downloads/os-win32.html.
mysql_init() NULL ,
MYSQL.

1.3 MySQL Java Connectivity (JDBC)


JDBC MySQL (mm driver
Reisin JDBC driver) ,
. mm driver
http://mmmysql.sourceforge.net/ http://www.mysql.com/Downloads/Contrib.
Reisin driver http://www.caucho.com/projects/jdbc-mysql/index.xtp.
JDBC
MySQL- .
1.4 MySQL Python API
MySQL Contrib Python, Joseph
Skinner.
Python iODBC,
MySQL ( mxODBC).
1.5 MySQL Tcl API
Tcl at binevolve. , Contrib Tcl,
msqltcl 1.50.
1.6 MySQL Eiffel
MySQL Contrib Eiffel, Michael
Ravits.

2 MySQL C API
C API MySQL.
mysqlclient C .
MySQL C.
, , C API,
. clients
MySQL.

API ( Java)
mysqlclient, MySQL. , ,
, ,
,
.
. ,
(16 ),
( 16 ).
,
, .
.
,
SQL ( "- ")
( "--").
,
. , BLOB,
16M , 16M
( ).
16M, 1M.
, max_allowed_packet
.
MySQL net_buffer_length
. , ,
, .
, "2.8
". ,
(
MySQL) "2.9 libmysqld,
MySQL".
2.1 C API
MYSQL

.
MySQL.

MYSQL_RES

,
(SELECT, SHOW, DESCRIBE, EXPLAIN). , ,
.
MYSQL_ROW

- .
.
,

,
. ,
mysql_fetch_row().
MYSQL_FIELD

, ,
, . .
MYSQL_FIELD ,
mysql_fetch_field(). ,
MYSQL_ROW.

MYSQL_FIELD_OFFSET

- MySQL.
mysql_field_seek().
, .
my_ulonglong

, mysql_affected_rows(),
mysql_num_rows() mysql_insert_id().
0 1.84e19.
my_ulonglong . ,
unsigned long %lu.
:
printf (Number of rows: %lu\n",
(unsigned long) mysql_num_rows(result));

MYSQL_FIELD , :
char * name

, .
char * table

, , .
, table .

char * def

,
. , mysql_list_fields().
enum enum_field_types type
. type

Type

FIELD_TYPE_TINY

TINYINT

FIELD_TYPE_SHORT

SMALLINT

FIELD_TYPE_LONG

INTEGER

FIELD_TYPE_INT24

MEDIUMINT

FIELD_TYPE_LONGLONG

BIGINT

FIELD_TYPE_DECIMAL

DECIMAL

FIELD_TYPE_FLOAT

FLOAT

FIELD_TYPE_DOUBLE

DOUBLE

NUMERIC

REAL

FIELD_TYPE_TIMESTAMP TIMESTAMP

FIELD_TYPE_DATE

DATE

FIELD_TYPE_TIME

TIME

FIELD_TYPE_DATETIME

DATETIME

FIELD_TYPE_YEAR

YEAR

FIELD_TYPE_STRING

(CHAR VARCHAR)

FIELD_TYPE_BLOB

TEXT ( max_length,
)
BLOB

FIELD_TYPE_SET

SET

FIELD_TYPE_ENUM

ENUM

FIELD_TYPE_NULL

NULL

: FIELD_TYPE_TINY
IS_NUM(),
. type IS_NUM(). TRUE,
:

FIELD_TYPE_CHAR

if (IS_NUM(field->type)) printf("Field is numeric\n");

unsigned int length

, .
unsigned int max_length

(
).
mysql_store_result() mysql_list_fields(),
. mysql_use_result(),
.

unsigned int flags

. flags
:
Flag

NOT_NULL_FLAG
NULL

UNSIGNED_FLAG




UNSIGNED

ZEROFILL_FLAG

ZEROFILL

BINARY_FLAG

BINARY

AUTO_INCREMENT_FLAG

AUTO_INCREMENT

ENUM_FLAG

ENUM

BLOB_FLAG

BLOB TEXT

PRI_KEY_FLAG
UNIQUE_KEY_FLAG
MULTIPLE_KEY_FLAG

TIMESTAMP
BLOB_FLAG, ENUM_FLAG TIMESTAMP_FLAG
, , .
TIMESTAMP_FLAG

field->type FIELD_TYPE_BLOB, FIELD_TYPE_ENUM


FIELD_TYPE_TIMESTAMP.
flags:
if (field->flags & NOT_NULL_FLAG) printf("Field can't be null\n");

,
flags:
IS_NOT_NULL(flags) , NOT NULL
IS_PRI_KEY(flags) ,
IS_BLOB(flags)
, BLOB TEXT
unsigned int decimals

.
2.2 C API
, C API,
. "2.3 C API".
mysql_affected_rows()


UPDATE, DELETE INSERT.

mysql_close()
mysql_connect()

.
.

mysql_change_user()
.

mysql_character_set_name()
.
. SQL CREATE
mysql_create_db()
DATABASE.
mysql_data_seek()
mysql_debug()
mysql_drop_db()
mysql_dump_debug_info()
mysql_eof()
mysql_errno()
mysql_error()
mysql_real_escape_string()


.
DBUG_PUSH .
.
SQL DROP DATABASE.

.
,
.

MySQL.

MySQL.

mysql_escape_string()
mysql_fetch_field()
mysql_fetch_field_direct()
mysql_fetch_fields()
mysql_fetch_lengths()
mysql_fetch_row()
mysql_field_seek()
mysql_field_count()
mysql_field_tell()
mysql_free_result()
mysql_get_client_info()
mysql_get_host_info()
mysql_get_proto_info()
mysql_get_server_info()
mysql_info()
mysql_init()
mysql_insert_id()
mysql_kill()
mysql_list_dbs()
mysql_list_fields()
mysql_list_processes()
mysql_list_tables()
mysql_num_fields()

SQL,

.

SQL.
.
, .
.

() .
.

.

.
,
mysql_fetch_field().
,
.
.
, .
,
.
.

.
MYSQL.
ID,
AUTO_INCREMENT .
.
,
.
,
.
.
,
.
.

mysql_num_rows()
mysql_options()
mysql_ping()
mysql_query()
mysql_real_connect()
mysql_real_query()
mysql_reload()
mysql_row_seek()
mysql_row_tell()
mysql_select_db()
mysql_shutdown()
mysql_stat()
mysql_store_result()
mysql_thread_id()
mysql_thread_safe()
mysql_use_result()

.

mysql_connect().
,
.
SQL,
.
.
SQL,
.
,
.
,
, mysql_row_tell().
.
.
.
.
.
ID .
1,
-.
.

, mysql_init(),
, mysql_real_connect()
( hostname, ).
mysql_real_connect() reconnect (
MYSQL) 1. ,
- ,
.
, mysql_close() .
, SQL
, mysql_query() mysql_real_query().
, mysql_query() ,
, mysql_real_query()
. (
),
mysql_real_query().

-SELECT (, INSERT, UPDATE, DELETE),


, , mysql_affected_rows().
SELECT .
, SELECT ,
. SHOW, DESCRIBE EXPLAIN.
, SELECT.
, .
, ,
mysql_store_result(). ,
.
, mysql_use_result().
, .
, mysql_fetch_row().
mysql_store_result() mysql_fetch_row() ,
. mysql_use_result() mysql_fetch_row()
.
mysql_fetch_lengths().
, ,
mysql_free_result(), .
.
, .
,
mysql_store_result().
mysql_store_result() , ,
,
, ,
mysql_data_seek() mysql_row_seek(),
() .
, , mysql_num_rows(). ,
mysql_store_result()
, , ,
.
mysql_use_result() ,
,
( ,
, mysql_use_result()
). : ,
.
(

), , ,
. , ,
, ,
.
API (
) , ,
SELECT. , mysql_store_result()
mysql_query() ( mysql_real_query()).
, SELECT, .
, mysql_field_count(), ,
. mysql_field_count() ,
( , INSERT, UPDATE,
DELETE - ) . mysql_field_count()
, , .
, SELECT, .
mysql_store_result() mysql_use_result()
, (
, , ..).
, mysql_fetch_field() ,
, mysql_fetch_field_direct() .
()
mysql_field_seek().
mysql_fetch_field().
, mysql_fetch_fields().
MySQL
mysql_errno() mysql_error().

, , , .
2.3 C API
NULL NULL
C, MySQL- NULL.
, , .
, , ,
-NULL, , NULL, ,
, , ,
, , . ,
" " .
, - ,
.

if (result)
... error ...
if (result < 0)
... error ...
if (result == -1)
... error ...

/* */
/* */
/* */

,
. ,
, mysql_errno().
, mysql_error().
2.3.1 mysql_affected_rows()
my_ulonglong mysql_affected_rows(MYSQL *mysql)

2.3.2

, UPDATE,
DELETE INSERT.
mysql_query() UPDATE, DELETE INSERT.
SELECT mysql_affected_rows() mysql_num_rows().
2.3.3

, , , .
, . -1 ,
, SELECT mysql_affected_rows()
mysql_store_result().
2.3.4

.
2.3.5
mysql_query(&mysql,"UPDATE products SET cost=cost*1.25 WHERE group=10");
printf("%ld products updated",(long) mysql_affected_rows(&mysql));

CLIENT_FOUND_ROWS, mysqld
mysql_affected_rows() , WHERE
UPDATE.

, , REPLACE,
mysql_affected_rows() 2 ,
, .
2.3.6 mysql_close()
void mysql_close(MYSQL *mysql)

2.3.7

. mysql_close()
, mysql,
mysql_init() mysql_connect().
2.3.8

.
2.3.9

.
2.3.10 mysql_connect()
MYSQL *mysql_connect(MYSQL *mysql, const char *host, const char *user,
const char *passwd)

2.3.11

MySQL host.
mysql_connect() ,
API, mysql_get_client_info().
,
mysql_real_connect() ,
NULL. C API
, mysql_close().
, ,
.
mysql_errno() mysql_error(),
MYSQL.
2.3.12

mysql_real_connect().
2.3.13

mysql_real_connect().
2.3.14 mysql_change_user()
my_bool mysql_change_user(MYSQL *mysql, const char *user, const char
*password, const char *db)

2.3.15

, db,
() ,
mysql.
, .
MySQL Version 3.23.3.
,
, .
.
mysql_change_user()

db NULL,
.
2.3.16

. , .
2.3.17

mysql_real_connect().
CR_COMMANDS_OUT_OF_SYNC

CR_SERVER_GONE_ERROR

MySQL .
CR_SERVER_LOST

CR_UNKNOWN_ERROR

.
ER_UNKNOWN_COM_ERROR

MySQL (, ).

ER_ACCESS_DENIED_ERROR

.
ER_BAD_DB_ERROR

ER_DBACCESS_DENIED_ERROR

.
ER_WRONG_DB_NAME

.
2.3.18
if (mysql_change_user(&mysql, "user", "password", "new_database"))
{
fprintf(stderr, "Failed to change user. Error: %s\n",
mysql_error(&mysql));
}

2.3.19 mysql_character_set_name()
const char *mysql_character_set_name(MYSQL *mysql)

2.3.20

()
.
2.3.21


2.3.22

.
2.3.23 mysql_create_db()
int mysql_create_db(MYSQL *mysql, const char *db)

2.3.24

db.
2.3.25

, . ,
.
2.3.26
CR_COMMANDS_OUT_OF_SYNC

CR_SERVER_GONE_ERROR

MySQL .
CR_SERVER_LOST

CR_UNKNOWN_ERROR

. .
2.3.27
if (mysql_create_db(&mysql, "my_database"))
{
fprintf(stderr, "Failed to create new database. Error: %s\n",
mysql_error(&mysql));
}

2.3.28 mysql_data_seek()
void mysql_data_seek(MYSQL_RES *result, unsigned long long offset)

2.3.29

. ,
,
mysql_data_seek()
mysql_store_result(), mysql_use_result().
0 mysql_num_rows(result)1.
2.3.30

.
2.3.31

.
2.3.32 mysql_debug()
void mysql_debug(char *debug)

2.3.33

DBUG_PUSH . mysql_debug()
Fred Fish. ,
, .
2.3.34

2.3.35

.
2.3.36

, ,
/tmp/client.trace :
mysql_debug("d:t:O,/tmp/client.trace");

2.3.37 mysql_drop_db()
int mysql_drop_db(MYSQL *mysql, const char *db)

2.3.38

, db.
2.3.39

, . ,
.
2.3.40
CR_COMMANDS_OUT_OF_SYNC

.
CR_SERVER_GONE_ERROR

MySQL .

CR_SERVER_LOST

.
CR_UNKNOWN_ERROR

.
2.3.41
if (mysql_drop_db(&mysql, "my_database"))
fprintf(stderr, "Failed to drop the database: Error: %s\n",
mysql_error(&mysql));

2.3.42 mysql_dump_debug_info()
int mysql_dump_debug_info(MYSQL *mysql)

2.3.43

,
. process,
.
2.3.44

, . ,
.
2.3.45
CR_COMMANDS_OUT_OF_SYNC

CR_SERVER_GONE_ERROR

MySQL .
CR_SERVER_LOST

CR_UNKNOWN_ERROR

.
2.3.46 mysql_eof()
my_bool mysql_eof(MYSQL_RES *result)

2.3.47
mysql_eof()

, .


mysql_store_result(), .
NULL mysql_fetch_row() ,
mysql_eof().
, mysql_use_result(),
,
, mysql_fetch_row() .
,
NULL mysql_fetch_row() ,
. , mysql_eof(),
, . mysql_eof() ,
, ,
.
mysql_eof() MySQL
mysql_errno() mysql_error().
, mysql_eof().
, ,

,
.
mysql_eof()

2.3.48

mysql_eof() , ,
, .
2.3.49

.
2.3.50

, mysql_eof():
mysql_query(&mysql,"SELECT * FROM some_table");
result = mysql_use_result(&mysql);
while((row = mysql_fetch_row(result)))
{
// -
}
if (!mysql_eof(result)) // mysql_fetch_row() -
{
fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
}

,
MySQL:
mysql_query(&mysql,"SELECT * FROM some_table");
result = mysql_use_result(&mysql);
while((row = mysql_fetch_row(result)))
{
// -
}
if (mysql_errno(&mysql))
// mysql_fetch_row() -
{
fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
}

2.3.51 mysql_errno()
unsigned int mysql_errno(MYSQL *mysql)

2.3.52

, mysql, mysql_errno()
API,

. 0 , .
MySQL errmsg.h.
mysqld_error.h.
MySQL
Docs/mysqld_error.txt.
2.3.53

. 0, .
2.3.54

.
2.3.55 mysql_error()
char *mysql_error(MYSQL *mysql)

2.3.56

, mysql, mysql_error()
API,
. ("") ,
. , :
if (mysql_errno(&mysql))
{
// an error occurred
}
if (mysql_error(&mysql)[0] != '\0')
{
// an error occurred
}


MySQL.
.
2.3.57

, . ,
.
2.3.58

.
2.3.59 mysql_escape_string()

mysql_real_escape_string() ,
. mysql_real_escape_string()
() ,
mysql_escape_string() charset.
2.3.60 mysql_fetch_field()
MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *result)

2.3.61


MYSQL_FIELD. ,
. mysql_fetch_field()
NULL, .
,
,
SELECT. , mysql_fetch_field()
mysql_field_seek().
mysql_fetch_field()

mysql_query() SELECT ,
mysql_store_result(), MySQL
blob (8K), mysql_fetch_field(),
BLOB. 8K , MySQL
BLOB.
-. , field->max_length

.
2.3.62

MYSQL_FIELD () . NULL,
.
2.3.63

.
2.3.64
MYSQL_FIELD *field;
while((field = mysql_fetch_field(result)))
{
printf("field name %s\n", field->name);
}

2.3.65 mysql_fetch_fields()
MYSQL_FIELD *mysql_fetch_fields(MYSQL_RES *result)

2.3.66

MYSQL_FIELD .
.
2.3.67

MYSQL_FIELD .
2.3.68

.
2.3.69
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);
}

2.3.70 mysql_fetch_field_direct()
MYSQL_FIELD *mysql_fetch_field_direct(MYSQL_RES *result, unsigned int
fieldnr)

2.3.71

fieldnr ,
MYSQL_FIELD.
, . fieldnr
0 mysql_num_fields(result)-1.
2.3.72

MYSQL_FIELD .
2.3.73

2.3.74
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);
}

2.3.75 mysql_fetch_lengths()
unsigned long *mysql_fetch_lengths(MYSQL_RES *result)

2.3.76

()
. ,
, strlen().
, ,
, ,
strlen() ,
.
, NULL,
. , ,
mysql_fetch_row().
2.3.77

,
( ). NULL, - .
2.3.78


. NULL,
mysql_fetch_row() .
mysql_fetch_lengths()

2.3.79
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]);
}
}

2.3.80 mysql_fetch_row()
MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)

2.3.81

.
mysql_store_result(), mysql_fetch_row() NULL,
, . mysql_use_result(),
mysql_fetch_row() NULL, , ,
.
mysql_num_fields(result). row
mysql_fetch_row(),
row[0] row[mysql_num_fields(result)-1]. NULL
NULL.
,
mysql_fetch_lengths(). , NULL 0.
, .
NULL, NULL, .
2.3.82

MYSQL_ROW . NULL, ,
, .
2.3.83
CR_SERVER_LOST

.
CR_UNKNOWN_ERROR

.
2.3.84
MYSQL_ROW row;

unsigned int num_fields;


unsigned int i;
num_fields = mysql_num_fields(result);
while ((row = mysql_fetch_row(result)))
{
unsigned long *lengths;
lengths = mysql_fetch_lengths(result);
for (i = 0; i < num_fields; i++)
{
printf("[%.*s] ", (int) lengths[i], row[i] ? row[i] : "NULL");
}
printf("\n");
}

2.3.85 mysql_field_count()
unsigned int mysql_field_count(MYSQL *mysql)

MySQL , Version 3.22.24,


unsigned int mysql_num_fields(MYSQL *mysql).
2.3.86

.
: mysql_store_result()
NULL (
). mysql_field_count(),
, mysql_store_result()
.
, , SELECT ( SELECT-).
, , .
2.3.87

, .
2.3.88

.
2.3.89
MYSQL_RES *result;
unsigned int num_fields;
unsigned int num_rows;
if (mysql_query(&mysql,query_string))
{

// error
}
else // query succeeded, process any data returned by it
{
result = mysql_store_result(&mysql);
if (result) // there are rows
{
num_fields = mysql_num_fields(result);
// retrieve rows, then call mysql_free_result(result)
}
else // mysql_store_result() returned nothing; should it have?
{
if (mysql_field_count(&mysql) == 0)
{
// query does not return data
// (it was not a SELECT)
num_rows = mysql_affected_rows(&mysql);
}
else // mysql_store_result() should have returned data
{
fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
}
}
}

: mysql_field_count(&mysql) mysql_errno(&mysql).
mysql_store_result()
mysql_field_count() ,
SELECT.
2.3.90 mysql_field_seek()
MYSQL_FIELD_OFFSET mysql_field_seek(MYSQL_RES *result,
MYSQL_FIELD_OFFSET offset)

2.3.91

.
mysql_fetch_field() ,
.
, 0 offset.
2.3.92

.
2.3.93

.
2.3.94 mysql_field_tell()

MYSQL_FIELD_OFFSET mysql_field_tell(MYSQL_RES *result)

2.3.95

,
mysql_fetch_field().
mysql_field_seek().
2.3.96

.
2.3.97

.
2.3.98 mysql_free_result()
void mysql_free_result(MYSQL_RES *result)

2.3.99

,
mysql_store_result(), mysql_use_result(), mysql_list_dbs()
. ,
, ,
mysql_free_result().
2.3.100

.
2.3.101

.
2.3.102 mysql_get_client_info()
char *mysql_get_client_info(void)

2.3.103

, .
2.3.104

, MySQL.

2.3.105

.
2.3.106 mysql_get_host_info()
char *mysql_get_host_info(MYSQL *mysql)

2.3.107

, ,
.
2.3.108

, .
2.3.109

.
2.3.110 mysql_get_proto_info()
unsigned int mysql_get_proto_info(MYSQL *mysql)

2.3.111

, .
2.3.112

, ,
() .
2.3.113

.
2.3.114 mysql_get_server_info()
char *mysql_get_server_info(MYSQL *mysql)

2.3.115

, .
2.3.116

, .
2.3.117

.
2.3.118 mysql_info()
char *mysql_info(MYSQL *mysql)

2.3.119

,
, , .
mysql_info() NULL.
, .
: , .
INSERT INTO ... SELECT ...
: Records: 100 Duplicates: 0 Warnings: 0
INSERT INTO ... VALUES (...),(...),(...)...
: Records: 3 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ...
: Records: 1 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE
: Records: 3 Duplicates: 0 Warnings: 0
UPDATE
: Rows matched: 40 Changed: 40 Warnings: 0

, mysql_info() -NULL
INSERT ... VALUES ,
.
2.3.120

,
. NULL,
.
2.3.121

.
2.3.122 mysql_init()
MYSQL *mysql_init(MYSQL *mysql)

2.3.123

MYSQL,
mysql_real_connect(). mysql NULL,
, .
, . mysql_init()
, ,
mysql_close().
2.3.124

MYSQL*. NULL, ,
.
2.3.125

NULL.
2.3.126 mysql_insert_id()
my_ulonglong mysql_insert_id(MYSQL *mysql)

2.3.127

ID,
AUTO_INCREMENT. ,
INSERT , AUTO_INCREMENT.
, mysql_insert_id() 0,
AUTO_INCREMENT.
,
mysql_insert_id() , .
INSERT UPDATE,
AUTO_INCREMENT,
LAST_INSERT_ID(expr).
mysql_insert_id()

, SQL LAST_INSERT_ID()
AUTO_INCREMENT,
,
.
2.3.128

AUTO_INCREMENT,
. 0, ,
AUTO_INCREMENT.

2.3.129

.
2.3.130 mysql_kill()
int mysql_kill(MYSQL *mysql, unsigned long pid)

2.3.131

, , pid.
2.3.132

. , .
2.3.133
CR_COMMANDS_OUT_OF_SYNC

.
CR_SERVER_GONE_ERROR

MySQL .

CR_SERVER_LOST

.
CR_UNKNOWN_ERROR

.
2.3.134 mysql_list_dbs()
MYSQL_RES *mysql_list_dbs(MYSQL *mysql, const char *wild)

2.3.135

, ,
,
wild. wild % _,
NULL, . mysql_list_dbs()
SHOW databases [LIKE wild].
mysql_free_result().
2.3.136

MYSQL_RES , NULL, .
2.3.137
CR_COMMANDS_OUT_OF_SYNC

.
CR_OUT_OF_MEMORY

CR_SERVER_GONE_ERROR

MySQL .
CR_SERVER_LOST

CR_UNKNOWN_ERROR

.
2.3.138 mysql_list_fields()
MYSQL_RES *mysql_list_fields(MYSQL *mysql, const char *table, const
char *wild)

2.3.139

, ,
,
wild. wild % _,
NULL, . mysql_list_fields()
SHOW COLUMNS FROM tbl_name [LIKE wild].
, , SHOW COLUMNS
FROM tbl_name mysql_list_fields().
mysql_free_result().
2.3.140

MYSQL_RES . NULL, .
2.3.141
CR_COMMANDS_OUT_OF_SYNC

CR_SERVER_GONE_ERROR

MySQL .
CR_SERVER_LOST

CR_UNKNOWN_ERROR

.
2.3.142 mysql_list_processes()
MYSQL_RES *mysql_list_processes(MYSQL *mysql)

2.3.143

, .
, mysqladmin processlist
SHOW PROCESSLIST.
mysql_free_result().
2.3.144

MYSQL_RES . NULL, .
2.3.145
CR_COMMANDS_OUT_OF_SYNC

CR_SERVER_GONE_ERROR

MySQL .
CR_SERVER_LOST

CR_UNKNOWN_ERROR

.
2.3.146 mysql_list_tables()
MYSQL_RES *mysql_list_tables(MYSQL *mysql, const char *wild)

2.3.147

, ,
,
wild. wild % _,
NULL, .
mysql_list_tables() SHOW tables [LIKE wild].
mysql_free_result().
2.3.148

MYSQL_RES . NULL, .
2.3.149
CR_COMMANDS_OUT_OF_SYNC

.
CR_SERVER_GONE_ERROR

MySQL .

CR_SERVER_LOST

.
CR_UNKNOWN_ERROR

.
2.3.150 mysql_num_fields()
unsigned int mysql_num_fields(MYSQL_RES *result)

unsigned int mysql_num_fields(MYSQL *mysql)

MySQL Version 3.22.24 .


MYSQL*, unsigned int
mysql_field_count(MYSQL *mysql).
2.3.151

.
,
.
, mysql_store_result() mysql_use_result()
NULL ( ).
mysql_field_count() ,
mysql_store_result() .
, ,
SELECT ( SELECT-). ,
, .
2.3.152

, .
2.3.153

.
2.3.154
MYSQL_RES *result;
unsigned int num_fields;
unsigned int num_rows;
if (mysql_query(&mysql,query_string))
{
// error
}
else // query succeeded, process any data returned by it
{
result = mysql_store_result(&mysql);

if (result) // there are rows


{
num_fields = mysql_num_fields(result);
// retrieve rows, then call mysql_free_result(result)
}
else // mysql_store_result() returned nothing; should it have?
{
if (mysql_errno(&mysql))
{
fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
}
else if (mysql_field_count(&mysql) == 0)
{
// query does not return data
// (it was not a SELECT)
num_rows = mysql_affected_rows(&mysql);
}
}
}

( ,
): mysql_errno(&mysql)
mysql_field_count(&mysql)=0.
2.3.155 mysql_num_rows()
my_ulonglong mysql_num_rows(MYSQL_RES *result)

2.3.156

.
mysql_num_rows() ,
mysql_store_result() mysql_use_result(),
. mysql_store_result(), mysql_num_rows()
. mysql_use_result(),
mysql_num_rows() ,
.
2.3.157

.
2.3.158

.
2.3.159 mysql_options()
int mysql_options(MYSQL *mysql, enum mysql_option option, const char
*arg)

2.3.160

,
.
, .
mysql_options()
mysql_connect()

mysql_init(),
mysql_real_connect().

option , ,
arg . , arg
.
:

MYSQL_OPT_CONNECT_TIMEOUT

unsigned int

*

MYSQL_OPT_COMPRESS

MYSQL_OPT_NAMED_PIPE

MYSQL_INIT_COMMAND

MYSQL_READ_DEFAULT_FILE

MYSQL_READ_DEFAULT_GROUP

.
,

MySQL

NT.
,
MySQL.
char *

.

char *
my.cnf.
char *


my.cnf
,
MYSQL_READ_DEFAULT_FILE.

, client ,
MYSQL_READ_DEFAULT_FILE MYSQL_READ_DEFAULT_GROUP.
:
connect_timeout
compress

. Linux
.
-.

database
debug
host
init-command

interactivetimeout
password
pipe
port
return-foundrows
socket
user

,
.
.
.
, MySQL.

, .
CLIENT_INTERACTIVE
mysql_real_connect(). "2.3.171
mysql_real_connect()".
.
,
MySQL, NT.
.
mysql_info() ,

UPDATE.
.
.

, timeout connect_timeout, timeout


.
2.3.161

. , .
2.3.162
MYSQL mysql;
mysql_init(&mysql);
mysql_options(&mysql,MYSQL_OPT_COMPRESS,0);
mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"odbc");
if (!mysql_real_connect(&mysql,"host","user","passwd",
"database",0,NULL,0))
{
fprintf(stderr, "Failed to connect to database: Error: %s\n",
mysql_error(&mysql));
}

-
odbc my.cnf.
2.3.163 mysql_ping()

int mysql_ping(MYSQL *mysql)

2.3.164

.
.
, ,
, ,
.
2.3.165

, . , .
2.3.166
CR_COMMANDS_OUT_OF_SYNC

.
CR_SERVER_GONE_ERROR

MySQL .

CR_UNKNOWN_ERROR

.
2.3.167 mysql_query()
int mysql_query(MYSQL *mysql, const char *query)

2.3.168

SQL, .
SQL.
(;) \g .
,
, mysql_real_query().
\0, mysql_query()
.
mysql_query()

, ,
mysql_field_count(), .
"2.3.85 mysql_field_count()".
2.3.169

, . , .

2.3.170
CR_COMMANDS_OUT_OF_SYNC

CR_SERVER_GONE_ERROR

MySQL .
CR_SERVER_LOST

CR_UNKNOWN_ERROR

.
2.3.171 mysql_real_connect()
MYSQL *mysql_real_connect(MYSQL *mysql, const char *host, const char
*user, const char *passwd, const char *db, unsigned int port, const
char *unix_socket, unsigned int client_flag)

2.3.172

MySQL,
host. mysql_real_connect()
, API,
mysql_get_client_info().
mysql_real_connect()


MYSQL. mysql_real_connect()
mysql_init(), MYSQL.
mysql_options().
"2.3.159 mysql_options()".
host IP. NULL
localhost, . OS
(Unix) (Windows),
TCP/IP,
.
user ID MySQL. user NULL,
. Unix ()
. Windows ODBC
.
passwd user. passwd NULL,
user, ,
.
MySQL ,
,
. :

mysql_real_connect():
.
db . db NULL,
.
port 0,
TCP/IP. , host
.
unix_socket NULL,
, . ,
host .
client_flag 0,
:


CLIENT_COMPRESS
.
,
CLIENT_FOUND_ROWS
.

CLIENT_IGNORE_SPACE .
.
interactive_timeout (
CLIENT_INTERACTIVE wait_timeout )
.
db_name.tbl_name.col_name.
ODBC.
,
CLIENT_NO_SCHEMA
,

ODBC.
CLIENT_ODBC
ODBC.
CLIENT_SSL
SSL.
2.3.173

MYSQL*, , NULL,
. , : ,
, NULL .
2.3.174
CR_CONN_HOST_ERROR

CR_CONNECTION_ERROR

CR_IPSOCK_ERROR

IP-.

CR_OUT_OF_MEMORY

.
CR_SOCKET_CREATE_ERROR

Unix-.

CR_UNKNOWN_HOST

IP- hostname.
CR_VERSION_ERROR


,
. ,
, ,
--old-protocol.

CR_NAMEDPIPEOPEN_ERROR

Windows.
CR_NAMEDPIPEWAIT_ERROR

Windows.

CR_NAMEDPIPESETSTATE_ERROR

Windows.
CR_SERVER_LOST
connect_timeout>

0 , connect_timeout ,
,
init-command, .

2.3.175
MYSQL mysql;
mysql_init(&mysql);
mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"your_prog_name");
if (!mysql_real_connect(&mysql,"host","user","passwd","database",
0,NULL,0))
{
fprintf(stderr, "Failed to connect to database: Error: %s\n",
mysql_error(&mysql));
}

mysql_options() MySQL
[client] your_prog_name my.cnf, ,
, - MySQL
.
, mysql_real_connect()
reconnect ( MYSQL) 1.
, -
, .
2.3.176 mysql_real_escape_string()

unsigned int mysql_real_escape_string(MYSQL *mysql, char *to, const


char *from, unsigned int length)

2.3.177

, ,
SQL.
from SQL,
() .
to .
NUL (ASCII 0), \n, \r, \, ', ", Control-Z, .
, from length .
length*2+1 .
,
.
mysql_escape_string() , to .
: , .
2.3.178
char query[1000],*end;
end = strmov(query,"INSERT INTO test_table values(");
*end++ = '\'';
end += mysql_real_escape_string(&mysql, end,"What's this",11);
*end++ = '\'';
*end++ = ',';
*end++ = '\'';
end += mysql_real_escape_string(&mysql, end,"binary data: \0\r\n",16);
*end++ = '\'';
*end++ = ')';
if (mysql_real_query(&mysql,query,(unsigned int) (end - query)))
{
fprintf(stderr, "Failed to insert row, Error: %s\n",
mysql_error(&mysql));
}

strmov(), , mysqlclient
strcpy(),
.
2.3.179

, to, .
2.3.180

.
2.3.181 mysql_real_query()
int mysql_real_query(MYSQL *mysql, const char *query, unsigned int
length)

2.3.182

SQL, query,
length . SQL.
(`;') \g .
mysql_real_query() mysql_query()
, , ,
\0. , mysql_real_query() ,
mysql_query() , strlen().
, ,
mysql_field_count(), .
"2.3.85 mysql_field_count()".
2.3.183

, . , .
2.3.184
CR_COMMANDS_OUT_OF_SYNC

CR_SERVER_GONE_ERROR

MySQL .
CR_SERVER_LOST

CR_UNKNOWN_ERROR

.
2.3.185 mysql_reload()
int mysql_reload(MYSQL *mysql)

2.3.186

, MySQL .
reload.
2.3.187

. , .
2.3.188
CR_COMMANDS_OUT_OF_SYNC

CR_SERVER_GONE_ERROR

MySQL .
CR_SERVER_LOST

CR_UNKNOWN_ERROR

.
2.3.189 mysql_row_seek()
MYSQL_ROW_OFFSET mysql_row_seek(MYSQL_RES *result, MYSQL_ROW_OFFSET
offset)

2.3.190


. ,
, mysql_row_seek()
mysql_store_result(), mysql_use_result().
, mysql_row_tell()
mysql_row_seek(). ,
, mysql_data_seek().
2.3.191

.
mysql_row_seek().
2.3.192

.
2.3.193 mysql_row_tell()
MYSQL_ROW_OFFSET mysql_row_tell(MYSQL_RES *result)

2.3.194

()
mysql_fetch_row().
mysql_row_seek().

mysql_row_tell() mysql_store_result(),
mysql_use_result().
2.3.195

() .
2.3.196

.
2.3.197 mysql_select_db()
int mysql_select_db(MYSQL *mysql, const char *db)

2.3.198

, db,
, mysql.
,
.
,
, .
mysql_select_db()

2.3.199

. , .
2.3.200
CR_COMMANDS_OUT_OF_SYNC

.
CR_SERVER_GONE_ERROR

MySQL .

CR_SERVER_LOST

.
CR_UNKNOWN_ERROR

.
2.3.201 mysql_shutdown()
int mysql_shutdown(MYSQL *mysql)

2.3.202

.
(shutdown).

2.3.203

. , .
2.3.204
CR_COMMANDS_OUT_OF_SYNC

CR_SERVER_GONE_ERROR

MySQL .
CR_SERVER_LOST

CR_UNKNOWN_ERROR

.
2.3.205 mysql_stat()
char *mysql_stat(MYSQL *mysql)

2.3.206

, ,
mysqladmin status. uptime ,
, , .
2.3.207

, . NULL,
.
2.3.208
CR_COMMANDS_OUT_OF_SYNC

.
CR_SERVER_GONE_ERROR

MySQL .

CR_SERVER_LOST

.
CR_UNKNOWN_ERROR

.
2.3.209 mysql_store_result()
MYSQL_RES *mysql_store_result(MYSQL *mysql)

2.3.210

mysql_store_result() mysql_use_result()
, (SELECT, SHOW, DESCRIBE, EXPLAIN).
mysql_store_result() mysql_use_result()
, ,
mysql_store_result() . , ...
, ,
mysql_store_result().
, ,
mysql_field_count(), .
"2.3.85 mysql_field_count()".
mysql_store_result() ,
MYSQL_RES .

,
( , , INSERT).
mysql_store_results()

,
. , ,
mysql_error() . mysql_errno() <>
0, mysql_field_count() <> 0, , .
mysql_store_results()

,
.
.
mysql_store_result() ,
, mysql_num_rows(), ,
.
mysql_fetch_row(),
, mysql_row_seek() mysql_row_tell(),
.
mysql_free_result()
.
2.3.211

MYSQL_RES . NULL, .
2.3.212
CR_COMMANDS_OUT_OF_SYNC

.
CR_OUT_OF_MEMORY

CR_SERVER_GONE_ERROR

MySQL .
CR_SERVER_LOST

CR_UNKNOWN_ERROR

.
2.3.213 mysql_thread_id()
unsigned long mysql_thread_id(MYSQL *mysql)

2.3.214

ID () .
mysql_kill(), .
, mysql_ping(), ID
. , ID
. ID .
2.3.215

ID () .
2.3.216

.
2.3.217 mysql_use_result()
MYSQL_RES *mysql_use_result(MYSQL *mysql)

2.3.218

mysql_store_result() mysql_use_result()
, (SELECT, SHOW, DESCRIBE, EXPLAIN).
,
mysql_store_result(). ,
,
mysql_fetch_row().
, ,
,
mysql_store_result().
mysql_use_result()

() ,
max_allowed_packet.
, mysql_use_result()
,
, ^S
( ).
, .
mysql_use_result()
mysql_fetch_row() , NULL,

. C API "Commands out of sync; You can't
run this command now", !
mysql_data_seek(), mysql_row_seek(),
mysql_row_tell(), mysql_num_rows() mysql_affected_rows() ,
mysql_use_result(),
, mysql_use_result(). , ,
, mysql_num_rows() .
mysql_free_result()
.
2.3.219

MYSQL_RES. NULL, .
2.3.220
CR_COMMANDS_OUT_OF_SYNC

CR_OUT_OF_MEMORY

.
CR_SERVER_GONE_ERROR

MySQL .

CR_SERVER_LOST

.
CR_UNKNOWN_ERROR

.
2.4 C
,
. "2.8 ".
2.4.1 my_init()

2.4.2


MySQL. .
- ,
mysql_thread_init().
mysql_init(), mysql_server_init()
mysql_connect().
2.4.3

.
2.4.4 mysql_thread_init()
2.4.5

,
.
my_init() mysql_connect().
2.4.6

.
2.4.7 mysql_thread_end()
2.4.8

pthread_exit(),
, mysql_thread_init().
, .
, .
2.4.9

.
2.5 C-
, ,
MySQL.
"2.9 libmysqld, MySQL ".

-lmysqlclient -lmysqld,
.
- .
2.5.1 mysql_server_init()
void mysql_server_init(int argc, const char **argv, const char **groups)

2.5.2


MySQL. (mysys,
InnoDB ..), . ,
.
argc argv main(). argv
( ). argc
0, .
NULL groups ,
. groups NULL,
[server].
2.5.3
#include <mysql.h>
#include <stdlib.h>
static char *server_args[] = {
"this_program",
/* this string is not used */
"--datadir=.",
"--set-variable=key_buffer_size=32M"
};
static char *server_groups[] = {
"server", "this_program_SERVER", (char *)NULL
};
int main(void) {
mysql_server_init(sizeof(server_args) / sizeof(char *),
server_args, server_groups);
/* Use any MySQL API functions here */
mysql_server_end();
return EXIT_SUCCESS;
}

2.5.4

.
2.5.5 mysql_server_end()

2.5.6

, . .
2.5.7

.
2.6 C API
2.6.1 mysql_query() mysql_store_result()
NULL?

, , :

malloc() (,
).
( ).
(, INSERT, UPDATE
DELETE).

,
, mysql_field_count(). mysql_field_count() ,
, ,
(, INSERT DELETE). mysql_field_count()
, .
mysql_error()
mysql_errno().
2.6.2 ?

, ,
:

,
INSERT, UPDATE DELETE.
: DELETE WHERE,
, !
mysql_affected_rows() .
mysql_num_rows() .
mysql_store_result() mysql_num_rows()
, mysql_store_result().
mysql_use_result() mysql_num_rows()
, mysql_fetch_row().
mysql_affected_rows()

ID, ,
AUTO_INCREMENT.
"2.3.126 mysql_insert_id()".
(LOAD DATA INFILE ..., INSERT INTO ... SELECT ...,
UPDATE) .
mysql_info(). mysql_info() NULL
.
mysql_insert_id()

2.6.3 ID
?

, ,
AUTO_INCREMENT, ID
mysql_insert_id().
ID, LAST_INSERT_ID()
, mysql_query().
, AUTO_INCREMENT,
. , INSERT
AUTO_INCREMENT:
if (mysql_error(&mysql)[0] == 0 &&
mysql_num_fields(result) == 0 && mysql_insert_id(&mysql) != 0)
{
used_id = mysql_insert_id(&mysql);
}

ID .
. ,
AUTO_INCREMENT
( , NULL 0).
ID,
, SQL
:
INSERT INTO foo (auto,text)
VALUES(NULL,'text');
INSERT INTO foo2 (id,text)
VALUES(LAST_INSERT_ID(),'text');

# generate ID by inserting NULL


# use ID in second table

2.6.4 C API

C API
:

gcc -g -o client test.o -L/usr/local/lib/mysql -lmysqlclient -lsocket -lnsl


Undefined
first referenced
symbol
in file
floor
/usr/local/lib/mysql/libmysqlclient.a(password.o)
ld: fatal: Symbol referencing errors. No output written to client

,
, -lm .
2.7
MySQL ,
, ,
-lmysqlclient -lz. -L,
, . ,
/usr/local/mysql/lib, -L/usr/local/mysql/lib
-lmysqlclient -lz .
, MySQL,
-I, (,
-I/usr/local/mysql/include), .
2.8
, net.c,
, .
, ,
.
SIGPIPE, -.

( Windows
-).
.
,

MySQL, -lmysys, -lstring -ldbug,
net_serv.o, .
,
- (mysqlclient_r)
.
net_serv.o MySQL.

,
, thr_alarm.c.
mysys, ,
my_init()! "2.4
C".
mysql_real_connect()
. ,
.
mysql_real_connect() mysql_connect().
mysql_real_connect() -,
:
shell> ./configure --enable-thread-safe-client

- libmysqlclient_r.
,
:

MySQL
. ,
mysql_query() mysql_store_result()
.
,
mysql_store_result().
mysql_use_result, ,
-
, .
,
mutex
mysql_query() mysql_store_result(). mysql_store_result()
, ,
.
POSIX,
pthread_mutex_lock() pthread_mutex_unlock(),
mutex.

, ,
MySQL, MySQL:
mysql_init() mysql_connect(), MySQL
,
.

MySQL ,
mysql_init() mysql_connect(),
, , ,
( , ). ,
:
1. my_init() ,
MySQL, mysql_real_connect().
2. mysql_thread_init()
MySQL.
3. mysql_thread_end() pthread_exit().
,
MySQL.
-
mysqlclient_r. ,
.
2.9 libmysqld, MySQL
2.9.1 MySQL

MySQL
MySQL .
: .
2.9.2 libmysqld

,
-lmysqld. mysql_config --libmysqld-libs
, . , , ,
libmysqld, .

,
.
2.9.3

Linux FreeBSD
.
. , ,
.

, example ,
mysql-4.0. example.c
GNUmakefile, GNU make example.
example.c:
/*
* A simple example client, using the embedded MySQL server library
*/
#include <mysql.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
enum on_error {E_okay, E_warn, E_fail};
static void die(MYSQL *db, char *fmt, ...);
MYSQL *db_connect(const char *dbname);
void db_disconnect(MYSQL *db);
void db_do_query(MYSQL *db, const char *query, enum on_error on_error);
const char *server_groups[] = { "test_client_SERVER", "server", NULL };
int main(int argc, char **argv)
{
MYSQL *one, *two;
/* This must be called before any other mysql functions.
*
* You can use mysql_server_init(0, NULL, NULL), and it will
* initialize the server using groups = { "server", NULL }.
*
* In your $HOME/.my.cnf file, you probably want to put:
[test_client_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_server_init(argc, argv, server_groups);
one = db_connect("test");
two = db_connect(NULL);
db_do_query(one, "show table status", E_fail);
db_do_query(two, "show databases", E_fail);
mysql_close(two);
mysql_close(one);
/* This must be called after all other mysql functions */
mysql_server_end();
exit(EXIT_SUCCESS);
}
void die(MYSQL *db, char *fmt, ...)

{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
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");
mysql_options(db, MYSQL_READ_DEFAULT_GROUP, "simple");
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);
}
/*
* show_query: this code is snagged from mysql.cc; this function
* is intended to be used internally to db_do_query()
*/
static char * show_query(MYSQL *db)
{
MYSQL_RES
*res;
MYSQL_FIELD *field;
MYSQL_ROW
row;
char sep[256], *psep = sep;
char *is_num = 0;
char *err = 0;
unsigned int length = 1;
/* initial "|" */
unsigned int off;
if (!(res = mysql_store_result(db))) return mysql_error(db);
if (!(is_num = malloc(mysql_num_fields(res))))
{
err = " ";
goto err;
}
/* set up */
*psep++ = '+';
while ((field = mysql_fetch_field(res)))
{
unsigned int len = strlen(field->name);
if (len < field->max_length) len = field->max_length;
if (len < 2 && !IS_NOT_NULL(field->flags)) len = 2; /* \N */
field->max_length = len + 1;
/* bending the API... */
len += 2; length += len + 1;
/* " " before, " |" after */
if (length >= 255)
{
err = "row too long";
goto err;
}
memset(psep, '-', len); psep += len;
*psep++ = '+';

*psep
= '\0';
}
/* column headings */
puts(sep);
mysql_field_seek(res,0);
fputc('|',stdout);
for (off=0; (field = mysql_fetch_field(res)) ; off++)
{
printf(" %-*s|",field->max_length, field->name);
is_num[off]= IS_NUM(field->type);
}
fputc('\n',stdout);
puts(sep);
/* rows */
while ((row = mysql_fetch_row(res)))
{
(void) fputs("|",stdout);
mysql_field_seek(res,0);
for (off=0; off < mysql_num_fields(res); off++)
{
field = mysql_fetch_field(res);
printf(is_num[off] ? "%*s |" : " %-*s|",
field->max_length, row[off] ? (char*) row[off] : "NULL");
}
(void) fputc('\n',stdout);
}
puts(sep);
err:
if (is_num) free(is_num);
mysql_free_result(res);
return err;
}
void db_do_query(MYSQL *db, const char *query, enum on_error on_error)
{
char *err = 0;
if (mysql_query(db, query) != 0) goto err;
if (mysql_field_count(db) > 0)
{
if ((err = show_query(db))) goto err;
}
else if (mysql_affected_rows(db))
printf("Affected rows: %lld [%s]\n",
mysql_affected_rows(db),query);
return;
err:
switch (on_error)
{
case E_okay: break;
case E_warn:
fprintf(stderr, "db_do_query failed: %s [%s]\n",
err ? err : mysql_error(db), query);
break;
case E_fail:
die(db, "db_do_query failed: %s [%s]",
err ? err : mysql_error(db), query);
break;
}
}

GNUmakefile:
# Set this to your mysql source directory
m
:= ../mysql-4.0
CC
:= cc
CPPFLAGS := -I$m/include -D_THREAD_SAFE -D_REENTRANT
CFLAGS
:= -g -W -Wall
LDFLAGS := -static
LDLIBS
= $(embed_libs) -lz -lm -lcrypt
ifneq (,$(shell grep FreeBSD /COPYRIGHT 2>/dev/null))
# FreeBSD
LDFLAGS += -pthread
else
# Assume Linux
LDLIBS += -lpthread
endif
# Standard libraries
embed_libs := \
$m/libmysqld/.libs/libmysqld.a \
$m/isam/libnisam.a \
$m/myisam/libmyisam.a \
$m/heap/libheap.a \
$m/merge/libmerge.a \
$m/myisammrg/libmyisammrg.a
# Optionally-built libraries
ifneq (,$(shell test -r $m/innobase/usr/libusr.a && echo "yes"))
embed_libs += \
$m/innobase/usr/libusr.a \
$m/innobase/odbc/libodbc.a \
$m/innobase/srv/libsrv.a \
$m/innobase/que/libque.a \
$m/innobase/srv/libsrv.a \
$m/innobase/dict/libdict.a \
$m/innobase/ibuf/libibuf.a \
$m/innobase/row/librow.a \
$m/innobase/pars/libpars.a \
$m/innobase/btr/libbtr.a \
$m/innobase/trx/libtrx.a \
$m/innobase/read/libread.a \
$m/innobase/usr/libusr.a \
$m/innobase/buf/libbuf.a \
$m/innobase/ibuf/libibuf.a \
$m/innobase/eval/libeval.a \
$m/innobase/log/liblog.a \
$m/innobase/fsp/libfsp.a \
$m/innobase/fut/libfut.a \
$m/innobase/fil/libfil.a \
$m/innobase/lock/liblock.a \
$m/innobase/mtr/libmtr.a \
$m/innobase/page/libpage.a \
$m/innobase/rem/librem.a \
$m/innobase/thr/libthr.a \
$m/innobase/com/libcom.a \
$m/innobase/sync/libsync.a \
$m/innobase/data/libdata.a \
$m/innobase/mach/libmach.a \
$m/innobase/ha/libha.a \
$m/innobase/dyn/libdyn.a \

$m/innobase/mem/libmem.a \
$m/innobase/sync/libsync.a \
$m/innobase/ut/libut.a \
$m/innobase/os/libos.a \
$m/innobase/ut/libut.a
endif
ifneq (,$(shell test -r $m/bdb/build_unix/libdb.a && echo "yes"))
embed_libs += $m/bdb/build_unix/libdb.a
endif
# Support libraries
embed_libs += \
$m/mysys/libmysys.a \
$m/strings/libmystrings.a \
$m/dbug/libdbug.a \
$m/regex/libregex.a
# Optionally built support libraries
ifneq (,$(shell test -r $m/readline/libreadline.a && echo "yes"))
embed_libs += $m/readline/libreadline.a
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

2.9.4

MySQL GNU GPL. :


, libmysqld MySQL,
(
, GPL).
,
GPL . ,
, : MySQL MySQL AB
.
2.10 MyC
2.10.1

MyC C, ,
MySQL
, , Microsoft DAO engine model (
Microsoft Access Microsoft Visual Basic).

MyC ,
: OpenDatabase, , OpenRecordset,
, Move, , AddNew/Edit
Update/Delete, ,
.
2.10.1.1

MyC 0.0.1 ALPHA.


2.10.1.2

MyC , , .
.
,
, Delete() .
DAO,
, .
MyC Linux,
UNIX. Windows .
MyC.
, ALPHA,
. ,
.
, ,
.
2.10.1.3

: Ed Carp. erc@pobox.com. www.pobox.com/~erc.


,
, C VB.
2.10.2
2.10.2.1

MyC
database.h. ,
.

, stdio.h stdlib.h.
#define MYC_DEBUG database.h,
stderr.
2.10.2.2

MyC ,
MySQL C API.
2.10.2.3

OpenDatabase() , ,
,
. EOF , NULL
.
OpenRecordset() SQL,
, .
OpenRecordset() EOF NULL .
RecordCount(),
.
2.10.2.4

MoveNext,
MovePrev, MoveFirst MoveLast, , ,
.
, EOF,
NULL.
2.10.2.5

,
GetField GetFieldN. GetField
EOF
. GetFieldN , ,
GetFieldN ( 0).
2.10.2.6

:
OpenRecordset() INSERT INTO UPDATE (
SQL),
AddNew Edit.
AddNew() ,
Update() SQL INSERT INTO.

Edit()
, Update()
SQL UPDATE.
SetField, SetFieldN
SetFieldB. SetField : ,
, . SetFieldN,
, . SetFieldB
, NULL ,
. , SetFieldB
.
, mysql_escape_string()
SetField SetFieldN.
, SetField
, , .
, Update() ,
. Update() EOF NULL .
, ,
() , .
Refresh() , OpenRecordset()
( 4096 ) OpenRecordset(), ,
, Refresh().
2.10.2.7

Delete() .
, .
2.10.2.8

,
RecordCount(), FieldCount(), AbsolutePosition() RecordsetEOF(). RecordCount
,
. FieldCount .
FieldValue ,
FieldName , .
AbsolutePosition .
RecordsetEOF TRUE,
,
, ,
. MoveLast MoveFirst RecordsetEOF TRUE.
2.10.2.9

MyC.
test mysql, 5
:
+--------+-----+
| name
| num |
+--------+-----+
| item 0 | 0 |
| item 1 | 1 |
| item 2 | 2 |
| item 3 | 3 |
| item 4 | 4 |
+--------+-----+

, ,
stdout:
#include "database.h"
main ()
{
int i;
OpenDatabase("mysql", NULL, NULL, NULL);
OpenRecordset("select * from test");
while(RecordsetEOF () != EOF)
{
for (i = 0; i < FieldCount(); i++) printf("%s\t", GetFieldN(i));
puts("");
MoveNext();
}
CloseRecordset();
CloseDatabase();
exit(0);
}

,
. test,
, , item 3 item 5
item 4:
#include "database.h"
main ()
{
int i;
char buf[10], buf2[5];
OpenDatabase("mysql", NULL, NULL, NULL);
OpenRecordset("delete from test");
CloseRecordset();
OpenRecordset("select * from test");
for (i = 0; i < 5; i++)
{
AddNew();
sprintf(buf, "item %d", i);

sprintf(buf2, "%d", i);


SetField("name", buf);
SetField("num", buf2);
Update("test");
}
Refresh();
MoveFirst();
while (RecordsetEOF () != EOF)
{
for (i = 0; i < FieldCount (); i++) printf("%s\t", GetFieldN(i));
puts("");
MoveNext();
}
MoveFirst ();
while (RecordsetEOF () != EOF)
{
printf ("Looking at '%s'\n", GetField ("name"));
if (strcmp(GetField("name"), "item 3") == 0)
{
puts("Changing data");
Edit();
SetField("name", "item 5");
Update("test");
}
if (strcmp(GetField("name"), "item 4") == 0)
{
puts("Deleting data");
Delete("test");
}
MoveNext();
}
CloseRecordset();
CloseDatabase();
exit(0);
}

3. C++ API
3.1. Mysql++.
3.1.1 Mysql++

Mysql++ C++ API Mysql (


SQL ). API:
, STL
3.1.2 Mysql++

Mysql++ web- mysql++


http://www.mysql.com/download_mysql++.html
3.1.3 Mysql++

( )
Mysql++
http://www.mysql.com/download_mysql++.html.
, mysql-plusplus@lists.mysql.com.
3.2.
Mysql++ API .
.
SQL API,
: 1) , 2)
, 3) .
.

, Mysql.
, -
.
.
, .

.
strstream, ,
. ,
.
Template .
Template
, .

( - )
, .
Query
-select (, ).

, ,
: .


,

. ,
constant string link class,
, ,
, .
C API.
.

, .
, .

, .
, , ,
. ,
.
,
. ,
, . ,
, .

, ,
. , ,
C API.
, C API . -

, C++,
SQL. ,
, C API, .

Standard Template Library (STL). ,
iterator, STL-.
,
STL-.

STL. ,
,
.

, ,
. ,
5- 3- result[3][5].
,
, , result[3]["price"], "price" 3- .
, ,
,
. :
,
, , mysql,
, ,
null. ,
,
. : MySQL++
.
, ()
C++, what().
.
-enable-exception, .
, -disable-exception,
MySQL++.
,
.
: 1) (: 1.5, 10,
"Dog", "Brown"), 2) (: age,
weight, what, color), 3) (: age = 1.5 AND weight = 10
AND what = "Dog" AND color = "Brown").
,

.


SQL. STL, , .
, ,
. - ,
, .
C++ structs.
.
STL- - STL,

. ,
STL-, STL . ,
. ,
, "price"
result[3].price.
result[3]["price"].
,
, , ,
.
,
, ,
. .

,
MySQL. ,
MySQL++ MySQLGUI, .
,
C++.
,
. M
N , N MySQL.
,
.

.
, ,
.

, , ,
, .
const string,
,
size() subscript ([]),
SQL, SQL C C++ API.
1.7, .
STL,
C++, , MySQL++ .
string_util.hh string_util.cc.

3.3.
3.3.1

SSQLS equal_list (cchar *,


Manip, cchar *) equal_list (cchar *, cchar *, Manip).
1.3 mysql++,
GNU , 2.95. 1.3, mysql++
,
C++ 2.95. - -
GNU 2.7.xx, 2.8.xx .
egcs 1.x.x. mysql++

.
- g++ 2.95.3 g++ 2.96.
Borland C++, VC++ Compaq
Tru64.
, SPARC Solaris
C++ gcc 2.95.2.
, mysql++
Solaris gcc version 2.95 19990728 (release).
``connection'' Connection Connection::connect
( Mysql) ,
. connect.
, 3.22.xx
connect,
real_connect.
3.23.xx.
Mysql++ Win32 Cygwin
Cygnus Inc.
Autoconf Automake .
Specialized SQL Structures ( Custom Mysql
Structures) mysql_ sql_.
, (false)
(true) , bool. ,
true false .
, ,
.
, MysqlString,
. MysqlString
, MysqlString s = mysql.host_info.
MysqlRow MysqlString MysqlColData.
,
,
( , ). ,
.

,
.
Mysql++ ,
<<.
Mysql++ INSERT,
UPDATE DELETE exec().
Mysql++ .
.
Mysql++ .
C++ what().
64 int
libmysqlclient.
, MySQL++,
MySQL.

3.3.2


MysqlString, ,
. ,
, MysqlString
, Mysql .
.

3.4.
3.4.1

, , Mysql++ API.
, , -
.
3.4.2

, C++ . ,
Standard Template Library (STL).
3.4.3

. ,
, ,
make.
reset-db. :
reset-db [host [user [password]]]

host, localhost.
,

. , ,
.
,
. ,
mysql_cpp_data.
reset-db ,
, .
3.4.4
3.4.4.1

, ,
. simple1.cc,
.
#include <iostream>
#include <iomanip>
#include <sqlplus.hh>
int main()
{
Connection con("mysql_cpp_data");
// The full format for the Connection constructor is
// Connection(cchar *db, cchar *host="", cchar *user="",
// cchar *passwd="")
// You may need to specify some of them if the
// database is not on
// the local machine or you database username is
// not the same as your
// login name, etc..
Query query = con.query();
// This creates a query object that is bound to con.
query << "select * from stock";
// You can write to the query object
// like you would any other ostrem
Result res = query.store();
// Query::store() executes the query
// and returns the results
cout << "Query: " <<query.preview() << endl;
// Query::preview() simply returns a
// string with the current query
// string in it.
cout << "Records Found: "<< res.size() <<
endl <<endl;
Row row;
cout.setf(ios::left);
cout << setw(17) << "Item" << setw(4)
<<"Num" << setw(7) <<"Weight"

<< setw(7) <<"Price" << "Date"


<<endl << endl;
Result::iterator i;
// The Result class has a read-only
// Random Access Iterator
for (i = res.begin(); i != res.end(); i++)
{
row = *i;
cout << setw(17) << row[0] << setw(4)
<< row[1] << setw(7) << row["weight"]
<< setw(7) <<row[3]
<< row[4] <<endl;
}
return 0;
}

3.4.4.2

,
ColData.
complic1.cc.
#include <iostream>
#include <iomanip>
#include <sqlplus.hh>
int main()
{
try
{ // its in one big try block
Connection con(use_exceptions);
con.connect("mysql_cpp_data");
// Here we broke making the connection into two calls.
// The first one creates the Connection object with the
// use exceptions option turned on and the second one
// makes the connection
Query query = con.query();
query << "select * from stock";
Result res = query.store();
cout << "Query: " <<query.preview() << endl;
cout << "Records Found: "<< res.size() <<
endl <<endl;
Row row;
cout.setf(ios::left);
cout << setw(17) << "Item" << setw(4)
<<"Num" << setw(7) <<"Weight"
<< setw(7) <<"Price" << "Date"
<<endl << endl;
Result::iterator i;
cout.precision(3);
for (i = res.begin(); i != res.end(); i++)
{
row = *i;
cout << setw(17) <<row["item"] <<
setw(4) <<row[1] << setw(7) <<
(double)row[2] << setw(7) <<(double)row[3];
Date date = row["sdate"];

// The ColData is implicitly converted to a date here.


cout.setf(ios::right);
cout.fill('0');
cout << setw(2) <<date.month << "-" <<
setw(2) << date.day << endl;
cout.fill(' ');
cout.unsetf(ios::right);
}
{

}
{

}
return 0;
catch (BadQuery er)
// handle any connection or
// query errors that may come up
cerr << "Error: " <<er.error << endl;
return -1;
catch (BadConversion er)
// handle bad conversions
cerr << "Error: Tried to convert \"" << er.data
<< "\" to a \"" << er.type_name
<<"\"." <<endl;
return -1;

}
}

.
:
use_exceptions ,
, ,
. , use_exceptions
con, query. ,
, use_exceptions , .
, , use_exceptions,
, .
1. ColData ,
.
: a)
, b) (.), (0) .
, ``1.25'' int,
, ``1.00'' int ,
.
3.4.4.3

,
, SQL. fieldinfo1.cc.
#include <iostream>
#include <iomanip>
#include <sqlplus.hh>

int main()
{
try
{ // its in one big try block
Connection con(use_exceptions);
con.connect("mysql_cpp_data");
Query query = con.query();
query << "select * from stock";
Result res = query.store();
cout << "Query: " <<query.preview() << endl;
cout << "Records Found: "<< res.size() <<
endl <<endl;
cout << "Query Info:\n";
cout.setf(ios::left);
for (unsigned int i = 0; i < res.size(); i++)
{
cout << setw(2) << i << setw(15) <<
res.names(i).c_str() << setw(15) <<
res.types(i).sql_name() << setw(20) <<
res.types(i).name() << endl;
}
cout << endl;
if (res.types(0) == typeid(string))
cout << "Field 'item' is of an sql
type which most closely resembles a\n"
<< "the c++ string type\n";
if (res.types(1) == typeid(short int))
cout << "Field 'num' is of an sql type
which most closely resembles a\n"
<< "the c++ short int type\n";
else if (res.types(1).base_type() == typeid(short int))
cout << "Field 'num' base type is of
an sql type which most closely \n"
<< "resembles a the c++ short int type\n";
return 0;
} catch (BadQuery er)
{
cerr << "Error: " << er.error << endl;
return -1;
} catch (BadConversion er)
{
cerr << "Error: Tried to convert \"" << er.data
<< "\" to a \"" << er.type_name
<< "\"." << endl;
return -1;
}
}

3.4.5 SQL
3.4.5.1

,
Specialized SQL Structures (SSQLS). : custom1.cc.
#include <iostream>
#include <iomanip>
#include <vector>

#include <sqlplus.hh>
#include <custom.hh>
sql_create_5 (stock, 1, 5, string, item, int, num, double, weight,
double, price, Date, sdate)
// this is calling a very complex macro which will create a custom
// struct "stock" which has the variables:
//
string item
//
int num
//
...
//
Date sdate
// defined as well methods to help populate the class from a mysql row
// among other things that I'll get too in a latter example
int main ()
{
try
{
Connection con (use_exceptions);
con.connect ("mysql_cpp_data");
Query query = con.query ();
query << "select * from stock";
vector < stock > res;
query.storein (res);
// this is storing the results into a vector of the custom struct
// "stock" which was created my the macro above.
cout.setf (ios::left);
cout << setw (17) << "Item" << setw (4)
<< "Num" << setw (7) << "Weight"
<< setw (7) << "Price" << "Date"
<< endl << endl;
cout.precision(3);
vector <stock>::iterator i;
for (i = res.begin (); i != res.end (); i++)
{
cout << setw (17) << i->item.c_str ()
<< setw (4) << i->num << setw (7)
<< i->weight << setw (7) <<
i->price << i->sdate << endl;
}
return 0;
} catch (BadQuery er)
{ // handle any connection
// or query errors that may come up
cerr << "Error: " << er.error << endl;
return -1;
} catch (BadConversion er)
{
// we still need to cache bad conversions incase something goes
// wrong when the data is converted into stock
cerr << "Error: Tried to convert \"" << er.data
<< "\" to a \"" << er.type_name
<< "\"." << endl;
return -1;
}
}

, SSQLS .
3.4.5.2

SSQLS , .
: custom2.cc.
#include
#include
#include
#include
#include

<iostream>
<vector>
<sqlplus.hh>
<custom.hh>
"util.hh"

sql_create_5(stock, 1, 5, string, item, int, num,


double, weight, double, price, Date, sdate)
int main()
{
try
{ // its in one big try block
Connection con(use_exceptions);
con.connect("mysql_cpp_data");
Query query = con.query();
stock row;
/* row.item = "Hot Dogs";
row.num = 100;
row.weight = 1.5;
row.price = 1.75;
row.sdate = "1998-09-25"; */
row.set("Hot Dogs", 100, 1.5, 1.75, "1998-09-25");
// populate stock
query.insert(row);
// form the query to insert the row
// the table name is the name of the struct by default
cout << "Query : " << query.preview() << endl;
// show the query about to be executed
query.execute();
// execute a query that does not return a result set
print_stock_table(query);
// now print the new table;
} catch (BadQuery er)
{
cerr << "Error: " <<er.error << endl;
return -1;
} catch (BadConversion er)
{
cerr << "Error: Tried to convert \"" << er.data
<< "\" to a \"" << er.type_name
<< "\"." <<endl;
return -1;
}
}

, reset-db
.
3.4.5.3

SSQLS. : custom3.cc.

#include <iostream>
#include <vector>
#include <sqlplus.hh>
#include <custom.hh>
#include "util.hh"
// util.hh/cc contains the print_stock_table function
sql_create_5(stock, 1, 5, string, item, int, num,
double, weight, double, price, Date, sdate)
int main()
{
try { // its in one big try block
Connection con(use_exceptions);
con.connect("mysql_cpp_data");
Query query = con.query();
query << "select * from stock where item = \"Hotdogs' Buns\" ";
Result res = query.store();
if (res.empty())
throw BadQuery("Hotdogs' Buns not found in table, run reset-db");
stock row = res[0];
stock row2 = row;
row.item = "Hotdog Buns";
// now change item
query.update(row2, row);
// form the query to replace the row
// the table name is the name of the struct by default
cout << "Query : " << query.preview() << endl;
// show the query about to be executed
query.execute();
// execute a query that does not return a result set
print_stock_table(query);
// now print the new table;
} catch (BadQuery er) {
cerr << "Error: " << er.error << endl;
return -1;
} catch (BadConversion er)
{
cerr << "Error: Tried to convert \"" << er.data
<< "\" to a \"" << er.type_name
<< "\"." << endl;
return -1;
}
}

, , where
item. reset-db
.
3.4.5.4 Less-Than-Comparable

SSQLS less-than-comparable. ,

. : custom4.cc.
#include <iostream>
#include <iomanip>

#include <vector>
#include <sqlplus.hh>
#include <custom.hh>
sql_create_5(stock, 1, 5, string,item, int,num, double,weight,
double,price, Date,sdate)
int main()
{
try
{ // its in one big try block
Connection con(use_exceptions);
con.connect("mysql_cpp_data");
Query query = con.query();
query << "select * from stock";
set <stock> res;
query.storein(res);
// here we are storing the elements in a set not a vector.
cout.setf (ios::left);
cout << setw (17) << "Item" << setw (4)
<< "Num" << setw (7) << "Weight"
<< setw (7) << "Price" << "Date"
<< endl << endl;
// Now we we iterate through the set.
// Since it is a set the list will
// naturally be in order.
set <stock>::iterator i;
cout.precision(3);
for (i = res.begin (); i != res.end (); i++)
{
cout << setw (17) << i->item.c_str ()
<< setw (4) << i->num
<< setw (7) << i->weight << setw (7)
<< i->price << i->sdate << endl;
}
i = res.find(stock("Hamburger Buns"));
if (i != res.end())
cout << "Hamburger Buns found. Currently " << i->num
<< " in stock.\n";
else cout << "Sorry no Hamburger Buns found in stock\n";
// Now we are using the set's find method to find out how many
// Hamburger Buns are in stock.
return 0;
} catch (BadQuery er)
{
cerr << "Error: " << er.error << endl;
return -1;
} catch (BadConversion er)
{
cerr << "Error: Tried to convert \"" << er.data
<< "\" to a \"" << er.type_name
<< "\"." << endl;
return -1;
}
}

3.4.6

MySQl++ 1.6 ,
, MySQL+

+, .
C++
.
(
), ,
, , . ,
, .
, , ++,
MySQL++.
3.4.6.1 BLOB

MySQL version 3.23,


. MySQL++.
,
.
#include <sys/stat.h>
#include <fstream>
#include <mysql++>
extern int
const char
const char
const char
const char
const char
const char

errno;
MY_DATABASE[]="telcent";
MY_TABLE[]="fax";
MY_HOST[]="localhost";
MY_USER[]="root";
MY_PASSWORD[]="";
MY_FIELD[]="fax";
// BLOB field

int main(int argc, char *argv[])


{
if (argc < 2)
{
cerr << "Usage: load_file full_file_path" <<
endl<< endl;
return -1;
}
Connection con(use_exceptions);
try
{
con.real_connect(MY_DATABASE,MY_HOST,MY_USER,MY_PASSWORD,3306,
(int)0,60,NULL);
Query query = con.query();
ostrstream strbuf;
ifstream In (argv[1],ios::in| ios::binary);
struct stat for_len;
if ((In.rdbuf())->is_open())
{
if (stat (argv[1],& for_len) == -1) return -1;
unsigned int blen = for_len.st_size;
if (!blen) return -1;
char *read_buffer= new char[blen];
In.read(read_buffer,blen);
string fill(read_buffer,blen);

strbuf << "INSERT INTO " << MY_TABLE


<<" (" << MY_FIELD <<
") VALUES(\"" << escape <<
fill << "\")";
query.exec(strbuf.str());
delete[] read_buffer;
}
else cerr << "Your binary file " << argv[1]
<< "could not be open, errno = " << errno;
return 0;
} catch (BadQuery er)
{
cerr << "Error: " <<er.error << " "
<<con.errnum() << endl;
return -1;
}
}

, , escape.
1.6,
ColData,
.
, ,
, .
, .
3.4.6.1 HTML BLOB

. , .
3.23.3 BLOB
, ,
, ,
.
#include <sqlplus.hh>
#define MY_DATABASE "telcent"
#define MY_TABLE "fax"
#define MY_HOST "localhost"
#define MY_USER "root"
#define MY_PASSWORD ""
#define MY_FIELD "fax" // BLOB field
#define MY_KEY "datet" // PRIMARY KEY
int main (int argc, char *argv[])
{
if (argc < 2)
{
cerr << "Usage: cgi_image primary_key_value" <<
endl<< endl;
return -1;
}
cout << "Content-type: image/jpeg" << endl;
Connection con(use_exceptions);
try

{
con.real_connect(MY_DATABASE,MY_HOST,MY_USER,MY_PASSWORD,3306,
(int)0,60,NULL);
Query query = con.query();
query << "SELECT" << MY_FIELD << "FROM "
<< MY_TABLE << " WHERE " << MY_KEY
<<" = " << argv[1];
ResUse res = query.use();
Row row=res.fetch_row();
long unsigned int *jj = res.fetch_lengths();
cout << "Content-length:" << *jj <<
endl<< endl;
fwrite(row.raw_data(0),1,*jj,stdout);
return 0;
} catch (BadQuery er)
{
cerr << "Error: " << er.error << " "
<< con.errnum() << endl;
return -1;
}
}

MySQL++,
1.6.
.
3.4.6.2 Select

,
, .
, MySQL++.
#include <sqlplus.hh>
#define MY_DATABASE "telcent"
#define MY_TABLE "nazivi"
#define MY_HOST "localhost"
#define MY_USER "root"
#define MY_PASSWORD ""
#define MY_FIELD "naziv"
#define MY_QUERY "SELECT URL from my_table as t1, my_table as t2 \\
where t1.field = t2.field"
int main (void)
{
Connection con(use_exceptions);
try
{
ostrstream strbuf;
unsigned int i=0;
con.real_connect(MY_DATABASE,MY_HOST,MY_USER,MY_PASSWORD,3306,
(int)0,60,NULL);
Query query = con.query();
query << MY_QUERY;
ResUse res = query.use();
Row row;

strbuf << "delete from " << MY_TABLE <<


" where " << MY_FIELD << " in (";
// for UPDATE just replace the above DELETE FROM with UPDATE statement
for (;row=res.fetch_row();i++) strbuf << row[0] << ",";
if (!i) return 0;
string output(strbuf.str());
output.erase(output.size()-1,1);
output += ")";
query.exec((const string&)output);
// cout << output << endl;
return 0;
} catch (BadQuery er)
{
cerr << "Error: " << er.error << " "
<< con.errnum() << endl;
return -1;
}
}

, MY_FIELD
.
. (
escape), .
. ,
false.
DELETE. UPDATE .
:
, . ,
max_allowed.
.
3.4.6.2

, SSQLS .
3.7.
3.4.7

Mysql++: .
, .
, /
. reset-db.cc.
#include <iostream>
#include <sqlplus.hh>
int main (int argc, char *argv[])
{
Connection connection(use_exceptions);
try
{ // the entire main block is one big try block;

if (argc == 1) connection.connect("");
else if (argc == 2) connection.connect("",argv[1]);
else if (argc == 3) connection.connect("",argv[1],argv[2]);
else if (argc <= 4) connection.connect("",argv[1],argv[2],argv[3]);
// create a new object and connect based on any (if any) arguments
// passed to main();
try
{
connection.select_db("mysql_cpp_data");
} catch (BadQuery er)
{
// if it couldn't connect to the database assume that it doesn't exist
// and try created it. If that does not work exit with an error.
connection.create_db("mysql_cpp_data");
connection.select_db("mysql_cpp_data");
}
Query query = connection.query(); // create a new query object
try
{ // ignore any errors here we hope to make this simpler soon
query.execute("drop table stock");
} catch (BadQuery er) {}
query << "create table stock (item char(20) not null,
num smallint," << "weight double,
price double, sdate date)";
query.execute(RESET_QUERY);
// send the query to create the table and execute it. The
// RESET_QUERY tells the query object to reset it self after
// execution
query << "insert into %5:table values (%q0, %q1, %2, %3, %q4)";
query.parse();
// set up the template query we will use to insert the data. The
// parse method call is important as it is what lets the query
// know that this is a template and not a literal string
query.def["table"] = "stock";
// This is setting the parameter named table to stock.
query.execute("Hamburger Buns", 56, 1.25, 1.1, "1998-04-26");
query.execute("Hotdogs' Buns",65, 1.1, 1.1, "1998-04-23");
query.execute("Dinner Roles", 75, 0.95, 0.97, "1998-05-25");
query.execute("White Bread", 87, 1.5, 1.75, "1998-09-04");
// The last parameter "table" is not specified here. Thus
// the default value for "table" is used which is "stock".
} catch (BadQuery er)
{ // handle any errors that may come up
cerr << "Error: " <<er.error << endl;
return -1;
}
}

3.3.5.

.
, ,
.
3.3.5.1 struct BadConversion

,
.

instantiable

coldata1.hh

public

BadConversion (const char* tn, const char* d, size_t r, size_t a)


size_t actual_size
const string data
size_t retrieved
const char* type_name

3.5.2 class BadNullConversion

, Null ,
.

instantiable

null1.hh
3.5.3 class Connection

instantiable

connection1.hh

public

Connection ()
Connection (bool te)
Connection (const char *db, const char *host = "", const char *user = "", const
char *passwd = "", bool te = true)
Connection (const char *db, const char *host, const char *user, const char
*passwd, uint port, my_bool compress = 1, unsigned int connect_timeout = 5,
bool te=true, cchar *socket_name = "")
int affected_rows ()
operator bool ()
success()
string clinet_info ()
void close ()
bool connect (cchar *db = "", cchar *host = "", cchar *user = "", cchar *passwd =
"")
bool connected () const
true,
bool create_db (string db)
bool drop_db (string db)
int errnum ()
string error ()

bool exec (const string &str)
ResNSel execute (const string &str)
ResNSel execute (const string &str, bool te)
st_mysql_options get_options (void) const
string host_info ()
string info ()
string infoo (void)
int insert_id ()
int kill (unsigned long pid)
bool lock ()
int ping (void)
int proto_info ()
void purge (void)
inline Query query ()
int read_options (enum mysql_option option, const char *arg)
bool real_connect (cchar *db = "", cchar *host = "", cchar *user = "", cchar
*passwd = "", uint port = 0, my_bool compress = 0, unsigned int connect_timeout
= 60, cchar *socket_name= "")
int refresh (unsigned int refresh_options)
bool reload ()
bool select_db (const char *db)
bool select_db (string db)
string server_info ()
bool shutdown ()
string stat ()

Result store (const string &str)


Result store (const string &str, bool te)
template class T void storein (deque T &con, const string &s)
template class T void storein (list T &con, const string &s)
template class T void storein (multiset T &con, const string &s)
template class T void storein (set T &con, const string &s)
template class T void storein (slist T &con, const string &s)
template class T void storein (vector T &con, const string &s)
template class Sequence void storein_sequence (Sequence &, const string &)
template class Set void storein_set (Set &, const string &)
TYPE. TYPE
STL.
bool success ()
true,
void unlock ()
ResUse use (const string &str)
ResUse use (const string &str, bool te)
~ Connection ()

Friend

friend Query
friend ResNSel
friend ResUse

3.5.4 struct Date

mysql.

instantiable

public mysql_date, public MysqlDTbase Date


datetime1.hh

Date mysql.
.
public

Date ()
Date (cchar* str)
Date (const string &str)
Date (const string &str)
short int compare (const Date& other) const

3.5.5 struct DateTime

Date Time mysql- DateTime.

instantiable

public mysql_date, public mysql_time, public MysqlDTbase DateTime


datetime1.hh

public

DateTime ()
DateTime (cchar* str)
DateTime (const string &str)
DateTime (const string &str)
short int compare (const DateTime& other) const
cchar* convert (cchar*)
ostream& out_stream (ostream&) const

3.5.6 class FieldNames

instantiable

public vector string


field_names1.hh

public

FieldNames ()
FieldNames (const ResUse *res)
FieldNames (int i)
FieldNames& operator = (const ResUse *res)
res.
FieldNames& operator = (int i)
i .
string& operator (int i)
.
const string& operator (int i) const
.
uint operator (string i) const
.

3.5.7 class FieldTypes

instantiable

public vector mysql_type_info


field_types1.hh

public

FieldTypes ()
FieldTypes (const ResUse *res)
FieldTypes (int i)
FieldTypes& operator = (const ResUse *res)
, res
FieldTypes& operator = (int i)
i .

mysql_type_info& operator (int i)


i.
const mysql_type_info& operator (int i) const
i.

3.5.8 class Fields

, mysql .

instantiable

public const_subscript_container Fields, Field


fields1.hh

public

Fields ()
Fields (ResUse *r)
const Field& operator (int i) const
const Field& operator (size_type i) const
size_type size () const
. i.

3.5.9 template class MysqlCmp class BinaryPred, class Cmp

instantiable

public unary_function const MysqlRow&, bool


compare1.hh

public

MysqlCmp (uint i, const BinaryPred &f, const CmpType &c)


bool operator () (const MysqlRow& cmp1) const

Protected

CmpType cmp2
BinaryPred func
unsigned int index

3.5.10 template class MysqlCmpCStr class BinaryPred

instantiable

public MysqlCmp BinaryPred, const char *


compare1.hh

public

MysqlCmpCStr (uint i, const BinaryPred &f, const char* c)


bool operator () (const MysqlRow& cmp1) const

3.5.11 template struct MysqlDTbase class T

abstract

datetime1.hh
public

virtual short int compare (const T &other) const


bool operator != (const T &other) const
bool operator (const T &other) const

bool operator = (const T &other) const


bool operator == (const T &other) const
bool operator (const T &other) const
bool operator = (const T &other) const

3.5.12 template class MysqlListInsert class T, class value_type =


typename T::value_type

instantiable

set1.hh
public

MysqlListInsert (T *o)
void operator () (const value_type &data)

3.5.13 template class MysqlSetInsert class T, class key_type =


typename T::key_

instantiable

set1.hh
public

MysqlSetInsert (T *o)
void operator () (const key_type &data)

3.5.14 template class Null class Type, class Behavior = NullisNull

null.

instantiable

null1.hh
public

Null ()
Null (Type x)
Null (const null_type &n)
Null null.
Type data
bool is_null
Null& operator = (const null_type &n)
Null& operator = (const null_type &n)
typedef Type value_type

3.5.15 struct NullisBlank

, Null.

instantiable

null1.hh

public

static const char * null_is ()


static ostream& null_ostr (ostream &o)

3.5.16 struct NullisNull

, Null.

instantiable

null1.hh

public

static null_type null_is ()


static ostream& null_ostr (ostream& o)

3.5.17 struct NullisZero

, Null.

instantiable

null1.hh

public

static int null_is ()


static ostream& null_ostr (ostream &o)

3.5.18 class Query

instantiable

public SQLQuery

query1.hh

SQLQuery. SQLQuery
Mysql , .

public

Query (Connection *m, bool te = false)


, .
Query (const Query &q)
string error ()
, .
bool exec (const string &str)
,
, .
,
, , INSERT UPDATE. SQLQuery.
template class T Query& insert (const T &v)
Query& operator = (const Query &q)
string preview ()
string preview (parms &p)
template class T Query& replace (const T &v)
bool success ()
, .
string().

3.5.19 struct ResNSel

,
.

instantiable

result1.hh

public

ResNSel ()
ResNSel (Connection *q)
operator bool ()
.
string info
.
int insert_id

int rows
.
bool success

3.5.20 class ResUse

instantiable

result1.hh

public

ResUse ()
ResUse (MYSQL_RES *result, Connection *m = NULL, bool te = false)
ResUse (const ResUse &other)
operator bool () const
unsigned int columns () const
bool eof () const
c api.
Field& fetch_field () const
c api field.
long unsigned int * fetch_lengths () const
c api.
Row fetch_row ()
c api.
inline string& field_name (int)
i.
inline const string& field_name (int) const
- i.
inline FieldNames& field_names ()
FieldNames.
inline const FieldNames& field_names () const
FieldNames.
inline int field_num (const string&) const
, str.
void field_seek (int field)
c api field.
inline mysql_type_info& field_type (int i)
mysql i.
inline const mysql_type_info& field_type (int) const
- mysql i.

inline FieldTypes& field_types ()


FieldTypes.
inline const FieldTypes& field_types () const
- FieldTypes.
const Fields& fields () const
Fields.
const Field& fields (unsigned int i) const
mysql i.
MYSQL_RES * mysql_result (void)
inline FieldNames& names ()
FieldNames.
inline const FieldNames& names () const
- FieldNames.
inline int names (const string& s) const
, str.
inline string& names (int i)
i.
inline const string& names (int i) const
i.
int num_fields () const
c api field.
bool operator != (const ResUse &other) const
inline ResUse& operator = (const ResUse &other)
bool operator == (const ResUse &other) const
void parent_leaving ()
void purge (void)
inline void reset_field_names ()
.
inline void reset_field_types ()
field_types .
inline void reset_names ()
.
inline void reset_types ()
.
string& table ()
.
const string& table () const
.
inline FieldTypes& types ()
FieldTypes.
inline const FieldTypes& types () const
- FieldTypes.
inline mysql_type_info& types (int i)
mysql i.
inline const mysql_type_info& types (int i) const
- mysql i.

~ ResUse ()

protected

Fields _fields
mutable FieldNames * _names
string _table
mutable FieldTypes * _types
void copy (const ResUse& other)
Connection * mysql
mutable MYSQL_RES * mysql_res
bool throw_exceptions, initialized

friend

friend Connection

3.5.21 class Result

instantiable

public ResUse, public const_subscript_container Result,Row,const Row


result1.hh

Random Access Container, LessThanComparable


Assignable. (Random Access Container),
Random Access Iterator Random Access Iterator.
public

Result ()
Result (MYSQL_RES *result, bool te = false)
Result (const Result &other)
void data_seek (uint offset) const
c api

const Row fetch_row () const


c api
int num_rows () const
c api
const Row operator (size_type i) const
i.
size_type rows () const
.
size_type size () const
.
virtual ~ Result ()

Friend

friend Connection

3.5.22 class Row

instantiable

public const_subscript_container Row,ColData,const ColData, public RowTemplate


Row, ResUse

row1.hh
public

Row ()
Row (MYSQL_ROW d, const ResUse *r, unsigned int *jj, bool te = false)
operator bool () const
true, - .
inline const ColData operator (const string &i) const
i.
.
inline const ColData operator (const string &i) const
i.
.
const ColData operator (int i) const

inline const ColData operator (size_type i) const


i.
const ResUse& parent () const
const char * raw_data (int i) const
Row& self ()
const Row& self () const
inline size_type size () const
.
~ Row ()

3.5.23 template class RowTemplate class ThisType, class Res

abstract

row1.hh
public

equal_list_ba FieldNames,ThisType,quote_type0 equal_list (const char *d = ",",


const char *e = " = ") const
template class Manip equal_list_ba FieldNames,ThisType,Manip equal_list
(const char *d, const char *e, Manip m) const
value_list_b FieldNames,quote_type0 field_list (bool t0, bool t1=false, bool
t2=false, bool t3=false, bool t4=false, bool t5=false, bool t6=false, bool t7=false,
bool t8=false, bool t9=false, bool ta=false, bool tb=false, bool tc=false) const
value_list_b FieldNames,quote_type0 field_list (const vector bool &vb) const
value_list_b FieldNames,quote_type0 field_list (const vector bool &vb) const
template class Manip value_list_ba FieldNames,Manip field_list (const char *d,
Manip m) const
template class Manip value_list_b FieldNames,Manip field_list (const char *d,
Manip m, bool t0, bool t1=false, bool t2=false, bool t3=false, bool t4=false, bool
t5=false, bool t6=false, bool t7=false, bool t8=false, bool t9=false, bool ta=false,
bool tb=false, bool tc=false) const
template class Manip value_list_b FieldNames,Manip field_list (const char *d,
Manip m, const vector bool &vb) const
template class Manip value_list_b FieldNames,Manip field_list (const char *d,
Manip m, string s0, string s1="", string s2="", string s3="", string s4="", string
s5="", string s6="", string s7="", string s8="", string s9="", string sa="", string
sb="", string sc="") const
value_list_b FieldNames,quote_type0 field_list (const char *d, bool t0, bool
t1=false, bool t2=false, bool t3=false, bool t4=false, bool t5=false, bool t6=false,
bool t7=false, bool t8=false, bool t9=false, bool ta=false, bool tb=false, bool tc

value_list_b FieldNames,quote_type0 field_list (const char *d, const vector bool


&vb) const
value_list_b FieldNames,quote_type0 field_list (const char *d, string s0, string
s1="", string s2="", string s3="", string s4="", string s5="", string s6="", string
s7="", string s8="", string s9="", string sa="", string sb="", string sc="") const
value_list_b FieldNames,quote_type0 field_list (string s0, string s1="", string
s2="", string s3="", string s4="", string s5="", string s6="", string s7="", string
s8="", string s9="", string sa="", string sb="", string sc="") const
virtual const Res & parent () const
value_list_b ThisType,quote_type0 value_list (bool t0, bool t1=false, bool
t2=false, bool t3=false, bool t4=false, bool t5=false, bool t6=false, bool t7=false,
bool t8=false, bool t9=false, bool ta=false, bool tb=false, bool tc=false) const
value_list_b ThisType,quote_type0 value_list (const vector bool &vb) const
value_list_b ThisType,quote_type0 value_list (const vector bool &vb) const
template class Manip value_list_ba ThisType,Manip value_list (const char *d,
Manip m) const
template class Manip value_list_b ThisType,Manip value_list (const char *d,
Manip m, bool t0, bool t1=false, bool t2=false, bool t3=false, bool t4=false, bool
t5=false, bool t6=false, bool t7=false, bool t8=false, bool t9=false, bool ta=false,
bool tb=false, bool tc=false) const
template class Manip value_list_b ThisType,Manip value_list (const char *d,
Manip m, const vector bool &vb) const
template class Manip value_list_b ThisType,Manip value_list (const char *d,
Manip m, string s0, string s1="", string s2="", string s3="", string s4="", string
s5="", string s6="", string s7="", string s8="", string s9="", string sa="", string
sb="", string sc="") const
value_list_b ThisType,quote_type0 value_list (const char *d, bool t0, bool
t1=false, bool t2=false, bool t3=false, bool t4=false, bool t5=false, bool t6=false,
bool t7=false, bool t8=false, bool t9=false, bool ta=false, bool tb=false, bool
tc=false) const
value_list_b ThisType,quote_type0 value_list (const char *d, const vector bool
&vb) const
value_list_b ThisType,quote_type0 value_list (const char *d, string s0, string
s1="", string s2="", string s3="", string s4="", string s5="", string s6="", string
s7="", string s8="", string s9="", string sa="", string sb="", string sc="") const
value_list_b ThisType,quote_type0 value_list (string s0, string s1="", string
s2="", string s3="", string s4="", string s5="", string s6="", string s7="", string
s8="", string s9="", string sa="", string sb="", string sc="") const
virtual ~ RowTemplate ()

protected

protected pure virtual ThisType& self ()


protected pure virtual const ThisType& self () const

3.5.24 struct SQLParseElement

instantiable

sql_query1.hh

public

SQLParseElement (string b, char o, char n)


string before
char num
char option

3.5.25 class SQLQuery

instantiable

public strstream

sql_query1.hh

. , ,
Connection. Query
, ,
Connection.
strstream. ,
, strstream
sprintf. (, ),
. . ,
, .
, ,

SQLQuery,
error() success().
public

SQLQuery ()
SQLQuery (const SQLQuery &q)
operator bool ()
SQLQueryParms def
.
string error () const
template class T SQLQuery& insert (const T &v)
mysql_query_define_const1 (string,str)
bool operator ! ()
,
. str(query_reset),
0 11. query_reset
DONT_RESET RESET_QUERY.
RESET_QUERY, reset() , .
,
, success() false.
null, .
SQLQuery& operator = (const SQLQuery &q)
void parse ()
template class T SQLQuery& replace (const T &v)
bool success () const

Protected

bool Success
char* errmsg
typedef SQLQueryParms parms
vector SQLParseElement parsed
vector string parsed_names
map string,int parsed_nums
void proc (parms &p)
typedef const SQLString& ss

Friend

friend SQLQueryParms

3.5.26 struct SQLQueryNEParms

, .

instantiable

sql_query1.hh

, .
public

SQLQueryNEParms (const char *c)


const char* error

3.5.27 class SQLQueryParms

instantiable

public vector SQLString


sql_query1.hh

SQLStrings.
public

SQLQueryParms ()
SQLQueryParms (SQLQuery *p)
bool bound ()
void clear ()
.
SQLQueryParms operator + (const SQLQueryParms &other) const
: 0 a, 1 b ..
.
SQLQueryParms & operator += (const SQLString &str)
.

SQLQueryParms & operator (const SQLString &str)


.
SQLString & operator (const char *str)
str.
const SQLString & operator (const char *str) const
str.
SQLString & operator (size_type n)
n.
const SQLString & operator (size_type n) const
n.
void set (ss a)
void set (ss a, ss b)
void set (ss a, ss b, ss c)
void set (ss a, ss b, ss c, ss d)
void set (ss a, ss b, ss c, ss d, ss e)
void set (ss a, ss b, ss c, ss d, ss e, ss f)
void set (ss a, ss b, ss c, ss d, ss e, ss f, ss g)
void set (ss a, ss b, ss c, ss d, ss e, ss f, ss g, ss h)
void set (ss a, ss b, ss c, ss d, ss e, ss f, ss g, ss h, ss i)
void set (ss a,ss b,ss c,ss d,ss e,ss f,ss g,ss h,ss i,ss j)
void set (ss a,ss b,ss c,ss d,ss e,ss f,ss g,ss h,ss i,ss j,ss k)
void set (ss a,ss b,ss c,ss d,ss e,ss f,ss g,ss h,ss i,ss j,ss k, ss l)

friend

friend Query

3.5.28 class SQLString

, -.

instantiable

public string

sql_string1.hh

, ,
mysql.

public

SQLString ()
SQLString (char i)
SQLString (const char *str)
SQLString (const char *str)
SQLString (double i)
SQLString (float i)
SQLString (int i)
SQLString (short int i)
SQLString (unsigned int i)
SQLString (unsigned int i)
SQLString (unsigned int i)
bool dont_escape
bool is_string
SQLString& operator = (const string& str)
SQLString& operator = (const string& str)
bool processed

3.5.29 template class Set class Container = set string

mysql.

instantiable

public Container

set1.hh
public

Set (const ColData &str)


Set (const ColData &str)
Set (const ColData &str)
ostream& out_stream (ostream &s) const
operator string ()

3.5.30 struct Time

mysql.

instantiable

public mysql_time, public MysqlDTbase Time


datetime1.hh

Time.
insert.
public

Time ()
Time (cchar* str)
Time (const string &str)
Time (const string &str)
short int compare (const Time& other) const

3.5.31 class const_string

, const char *.

instantiable

const_string1.hh

string.
, const char *. .
, const char *
.
public

const_iterator begin () const

const char* c_str () const


typedef const char* const_iterator
typedef const char* const_pointer
typedef const char& const_reference
const_string ()
const_string (const char *str)
const char* data () const
typedef int difference_type
const_iterator end () const
typedef const_iterator iterator
const_iterator , .
size_type length () const
size_type max_size () const
const_reference operator (size_type pos) const
typedef const_pointer pointer
typedef const_reference reference
typedef unsigned int size_type
typedef const char value_type

3.5.32 template class const_subscript_container class OnType, class


ValueType, class ReturnType = const ValueType&, class SizeType =
unsigned int, class DiffType = int

,
(Random Access Container).

abstract

resiter1.hh

: - *operator[] (SizeType)*
*size()*.
public

iterator begin () const


typedef iterator const_iterator
typedef value_type* const_pointer
typedef value_type& const_reference
typedef const ::reverse_iterator const_iterator const_reverse_iterator
typedef DiffType difference_type

bool empty () const


iterator end () const
typedef subscript_iterator const this_type, ReturnType, SizeType, DiffType
iterator
size_type max_size () const
virtual ReturnType operator (SizeType i) const
typedef value_type* pointer
reverse_iterator rbegin () const
typedef value_type& reference
reverse_iterator rend () const
typedef const ::reverse_iterator iterator reverse_iterator
virtual size_type size () const
typedef SizeType size_type
typedef const_subscript_container OnType,ValueType,ReturnType,SizeType,
DiffType this_type
typedef ValueType value_type

3.5.33 struct cstr_equal_to

instantiable

bin_char_pred

compare1.hh
public

bool operator () (const char *x, const char *y) const

3.5.34 struct cstr_greater

instantiable

bin_char_pred

compare1.hh
public

bool operator () (const char *x, const char *y) const

3.5.35 struct cstr_greater_equal

instantiable

bin_char_pred

compare1.hh
public

bool operator () (const char *x, const char *y) const

3.5.36 struct cstr_less

instantiable

bin_char_pred

compare1.hh
public

bool operator () (const char *x, const char *y) const

3.5.37 struct cstr_less_equal

instantiable

bin_char_pred

compare1.hh
public

bool operator () (const char *x, const char *y) const

3.5.38 struct cstr_not_equal_to

instantiable

bin_char_pred

compare1.hh

public

bool operator () (const char *x, const char *y) const

3.5.39 struct do_nothing_type1

instantiable

manip1.hh
public

do_nothing_type1 (ostream *o)


ostream * ostr

3.5.40 struct do_nothing_type2

instantiable

manip1.hh
public

do_nothing_type2 (SQLQueryParms *p)


SQLQueryParms * qparms

3.5.41 template struct equal_list_b class Seq1, class Seq2, class


Manip

instantiable

vallist1.hh
public

const char * delem


equal_list_b (const Seq1 &s1, const Seq2 &s2, const vector bool &f, const char
*d, const char *e, Manip m)
const char * equl
const vector bool fields
const Seq1 * list1
const Seq2 * list2
Manip manip

3.5.42 template struct equal_list_ba class Seq1, class Seq2, class


Manip

instantiable

vallist1.hh

public

const char * delem


equal_list_ba (const Seq1 &s1, const Seq2 &s2, const char *d, const char *e,
Manip m)
const char * equl
const Seq1 * list1
const Seq2 * list2
Manip manip

3.5.43 struct escape_type1

instantiable

manip1.hh
public

escape_type1 (ostream *o)


ostream * ostr

3.5.44 struct escape_type2

instantiable

manip1.hh
public

escape_type2 (SQLQueryParms *p)


SQLQueryParms * qparms

3.5.45 struct ignore_type2

instantiable

manip1.hh
public

ignore_type2 (SQLQueryParms *p)


SQLQueryParms * qparms

3.5.46 template class mysql_ColData class Str

.
.

instantiable

public Str

coldata1.hh

.
C. ,
, ,
. ,
, MysqlStr("12.86")+2 14, 2
. , NO_BINARY_OPERS
.
, .
. typedef ColData MutableColData.
public

template class T, class B operator Null T, B () const


operator cchar* () const
operator unsigned char () const
operator unsigned char () const
template class Type Type conv (Type dummy) const
TYPE.
TYPE, BadConversion. TYPE
, . :
.

operator double () const


bool escape_q () const
true false , .
inline const string& get_string (void) const
operator unsigned long int () const
operator unsigned long int () const
operator unsigned long int () const
operator unsigned long int () const
operator unsigned long int () const
operator unsigned long int () const
inline const bool is_null (void) const
void it_is_null (void)
mysql_ColData ()
bool quote_q () const
true false , .
mysql_type_info type ()
mysql .
operator ulonglong () const

3.5.47 class mysql_convert

instantiable

convert1.hh
3.5.48 struct mysql_date

instantiable

virtual public mysql_dt_base


datetime1.hh
public

cchar* convert (cchar*)


tiny_int day

tiny_int month
ostream& out_stream (ostream&) const
short int year

protected

short int compare (const mysql_date *other) const

3.5.49 struct mysql_dt_base

abstract

datetime1.hh
public

virtual ostream& out_stream (ostream&) const


operator string ()

3.5.50 class mysql_ti_sql_type_info

instantiable

type_info1.hh
friend

friend mysql_ti_sql_type_info_lookup
friend mysql_type_info

3.5.51 class mysql_ti_sql_type_info_lookup

instantiable

type_info1.hh

friend

friend mysql_type_info

3.5.52 struct mysql_time

instantiable

virtual public mysql_dt_base


datetime1.hh
public

cchar* convert (cchar*)


tiny_int hour
tiny_int minute
ostream& out_stream (ostream&) const
tiny_int second

protected

short int compare (const mysql_time *other) const

3.5.53 class mysql_type_info

, ColData.

instantiable

type_info1.hh

public

unsigned int _length

unsigned int _max_length


inline const mysql_type_info base_type () const
type_info C++ Null.
Null, c_type().
bool before (mysql_type_info &b)
. id()
.
inline const type_info& c_type () const
bool escape_q () const
true, sql ,
.
int id () const
id sql_type. :
,
.
inline const unsigned int length () const
inline const unsigned int max_length () const
type_info C++, sql.
mysql_type_info ()
mysql_type_info (const type_info &t)
mysql_type_info (const type_info &t)
inline mysql_type_info (const MYSQL_FIELD &f)
inline mysql_type_info (enum_field_types t, bool _unsigned, bool _null)
mysql_type_info (unsigned char n)
inline const char* name () const
, c++. ,
typeid().name() C++,
sql.
mysql_type_info& operator = (const type_info &t)
mysql_type_info& operator = (const type_info &t)
mysql_type_info& operator = (unsigned char n)
bool quote_q () const
true, sql .
inline const char* sql_name () const
sql.
static const unsigned char string_type

3.5.54 class null_type

instantiable

null1.hh

public

template class Type operator Type ()

3.5.55 struct quote_double_only_type1

instantiable

manip1.hh
public

ostream * ostr
quote_double_only_type1 (ostream *o)

3.5.56 struct quote_double_only_type2

instantiable

manip1.hh
public

SQLQueryParms * qparms
quote_double_only_type2 (SQLQueryParms *p)

3.5.57 struct quote_only_type1

instantiable

manip1.hh
public

ostream * ostr

quote_only_type1 (ostream *o)

3.5.58 struct quote_only_type2

instantiable

manip1.hh
public

SQLQueryParms * qparms
quote_only_type2 (SQLQueryParms *p)

3.5.59 struct quote_type1

instantiable

manip1.hh

public

ostream * ostr
quote_type1 (ostream *o)

3.5.60 struct quote_type2

instantiable

manip1.hh
public

SQLQueryParms * qparms

quote_type2 (SQLQueryParms *p)

3.5.61 template class simp_list_b class Iter

instantiable

vallist1.hh
public

Iter _begin
Iter _end
Iter begin () const
typedef Iter const_iterator
Iter end () const
simp_list_b (Iter b, Iter e)

3.5.62 template class subscript_iterator class OnType, class


ReturnType, class SizeType, class Diff

instantiable

public random_access_iterator ReturnType, SizeType


resiter1.hh
public

bool operator != (const subscript_iterator &j) const


ReturnType operator * () const
subscript_iterator operator + (SizeType n) const
subscript_iterator& operator ++ ()
subscript_iterator operator ++ (int)
subscript_iterator& operator += (SizeType n)
subscript_iterator operator - (SizeType n) const
DiffType operator - (const subscript_iterator &j) const
subscript_iterator& operator - ()

subscript_iterator operator - (int)


subscript_iterator& operator -= (SizeType n)
ReturnType operator - () const
bool operator (const subscript_iterator &j) const
bool operator = (const subscript_iterator &j) const
bool operator == (const subscript_iterator &j) const
bool operator (const subscript_iterator &j) const
bool operator = (const subscript_iterator &j) const
ReturnType operator (SizeType n) const
subscript_iterator ()
subscript_iterator (OnType *what, SizeType pos)

3.5.63 struct type_info_cmp

instantiable

type_info1.hh
public

bool operator() (const type_info *lhs, const type_info *rhs) const

3.5.64 template struct value_list_b class Seq, class Manip

instantiable

vallist1.hh
public

const char * delem


const vector bool fields
const Seq * list
Manip manip
value_list_b (const Seq &s, const vector bool &f, const char *d, Manip m)

3.5.65 template struct value_list_ba class Seq, class Manip

instantiable

vallist1.hh
public

const char * delem


const Seq * list
Manip manip
value_list_ba (const Seq &s, const char* d, Manip m)

3.5.66


<<. ostream (
SQLQuery Query, ostream) SQLQueryParms.
SQLQueryParms,
.
quote
.
ostream SQLQueryParms.
quote_only
, .
ostream SQLQueryParms.
quote_only_double
, . `` '.
escape
.
do_nothing
. ,
. SQLQueryParms,
, .
ignore
SQLQueryParms. do_nothing,
.
1.6,
. mysql_ColData.

<<, , , ,
strstream, . cout, cerr
clog. , (
) .
strstream.

,
dont_quote_auto true.
3.6.
,
,
.
3.6.1

,
, :
query << "select (%2:field1, %3:field2)
from stock where %1: wheref = %q0:what"

Query::parse(). :
query.parse()

3.6.2

:
select (%2:field1, %3:field2) from stock where %1:wheref = %q0:what

SQLQueryParms (
).
:
%(modifier)##(:name)(:)

Modifier :
%
"%".
""
"" .
q
, mysql_escape_string,
, char *, Mysql ,
.
Q

, , .
, ,
.
r
, .
R
, , .
## .
``:name'' ,
SQLQueryParms. -
. , ,
. ,
.
3.6.3

, ,
.
3.6.3.1

, ,
Query::store(const SQLString &parm0, [..., const SQLString
&parm11]) ( Query::use Query::execute).
parm0 0 . ,
. 1 12
. :
Result res = query.store("Dinner Roles", "item",
"item", "price")

3.6.2 :
select (item, price) from stock where item = " Dinner Roles"

, :
select (%0:field1, %1:field2) from stock where %2: wheref = %q3:what

.
3.6.3.2


def. def,
. .
:

query.def[0]
query.def[1]
query.def[2]
query.def[3]

=
=
=
=

"Dinner Roles";
"item";
"item";
"price";

:
query.def["what"] =
query.def["wheref"]
query.def["field1"]
query.def["field2"]

"Dinner Roles";
= "item";
= "item";
= "price";

.
, ,
. :
Result res = query.store()

3.6.3.3


def,
Query::store ( use execute)
. :
query.def["field1"] = "item";
query.def["field2"] = "price";
Result res1 = query.store("Hamburger Buns", "item");
Result res2 = query.store(1.25, "price");

:
select (item, price) from stock where item = "Hamburger Buns"

res1
select (item, price) from stock where price = 1.25

res2.
Query::store
( , ),
:
select (%0:field1, %1:field2) from stock where %2: wheref = %q3:what

.
select (%2:field1, %3:field2) from stock where %1: wheref = %q0:what

, wheref what.

, , , Query::store(const char* q)
q. , Query::store (use
execute), , const char*,
SQLString. :
Result res = query.store(SQLString("Hamburger Buns")).

3.6.3.4


, ,
def, SQLQueryNEParms.
, ,
SQLQueryNEParms::string. :
query.def["field1"] = "item";
query.def["field2"] = "price";
Result res = query.store(1.25);

SQLQueryNEParms , wheref
.
.
, , , (,
).
3.7. SQL
SQL (Specialized SQL Structures, SSQLS)
mysql
.
Standard Template Library (STL).
(structs).
. STL - STL,
. value_type
STL.
3.7.1 sql_create_basic

mysql
.
sql_create_basic_5(stock, 0, 0, string, item, int, num, double, weight,
double, price, MysqlDate, date)

struct stock
{
stock () {}
stock (const MysqlRow &row);
set (const MysqlRow &row);
string item;
int num;
double weight;
double price;
MysqlDate date;
};

, .
: stock (MysqlRow &row),
stock :
vector<stock> result;
query.storein(result);

,
, .
:
sql_create_basic_#(NAME, 0, 0, TYPE1, ITEM1, ... TYPE#, ITEM#)

# , NAME ,
, TYPE1 ,
ITEM1 ..
3.7.2 sql_create_basic

, 0
. , n
, :
sql_create_basic_5(stock, 1, 0, string, item, int, num, double, weight,
double, price, MysqlDate, date)

, ,
.

. n ,
. , n=2, item,
, num. num ,
.
struct stock
(
...
stock (const string &p1);
set (const string &p1);

bool operator == (const stock &other) const;


bool operator != (const stock &other) const;
bool operator > (const stock &other) const;
bool operator < (const stock &other) const;
bool operator >= (const stock &other) const;
bool operator <= (const stock &other) const;
int cmp (const stock &other) const;
int compare (const stock &other) const;
}
int compare (const stock &x, const stock &y);

int compare (const stock &x, const stock &y) x y


<0, x < y, 0 x=y >0, x > y. stock::cmp stock::compare
compare(*this, other).
stock::stock , p1
.
, :
x <= stock("Hotdog")

stock less-then-comparable,
:
set<stock> result;
query.storein(result);

, :
cout << result.lower_bound(stock("Hamburger"))->item
<< endl;

, Hamburger.
STL- ,
less-then-comparable.
:
sql_create_base_#(NAME, CMP, 0, TYPE1, ITEM1, ... TYPE#, ITEM#)

CMP , cmp ,
.
3.7.3 sql_create_basic


. m, ,
n . :

sql_create_basic_5(stock, 1, 5, string, item, int, num, double,


weight, double, price, MysqlDate, date)

:
struct stock
{
...
stock(const string&, const int&, const double&,
const double&, const MysqlDate&);
set(const string&, const int&, const double&,
const double&, const MysqlDate&);
}

3.7.4 sql_create_basic

sql_create_basic :
sql_create_basic_#(NAME, CMP, CNST, TYPE1, ITEM1, ..., TYPE#, ITEM#)

# .
NAME ,
CMP , 0, cmp ,
.
CNST , 0, ,
n .
TYPE1 , ITEM1
..

3.7.5 sql_create_basic_c_order

, mysql
. :
sql_create_basic_c_order_5(stock, 2, 5, MysqlDate, date, 5,
double, price, 4, string, item, 1,
int, num, 2, double, weight, 3)

,
, . ++
, (date, price). ,
, ,
. date 5- , price
4- .
3.7.6 sql_create_basic_c_order

, sql_create_basic :

sql_create_basic_c_order_#(NAME, CMP, CNST, TYPE1, ITEM1,


ORDER1, ... TYPE#, ITEM#, ORDER#)

# .

NAME ,
CMP , 0, cmp ,
.
CNST , 0, ,
n .
TYPE1 , ITEM1
, ORDER1 ..

3.7.7 sql_create


, ,
. :
sql_create_5(stock, 1, 5, string, item, int, num, double, weight,
double, price, MysqlDate, date)

, :
struct stock
{
...
static char *names[];
static char *table;
template <class Manip>
stock_value_list<Manip>
value_list(cchar *d = ",", Manip m = mysql_quote) const;
template <class Manip>
stock_field_list<Manip>
field_list(cchar *d = ",", Manip m = mysql_do_nothing) const;
template <class Manip>
stock_equal_list<Manip>
equal_list(cchar *d = ",",
cchar *e = " = ",
Manip m = mysql_quote,
) const;
template <class Manip>
stock_cus_value_list<Manip> value_list([cchar *d, [Manip m,]]
bool i1, bool i2 = false, ... ,
bool i5 = false) const;
template <class Manip>
stock_cus_value_list<Manip> value_list([cchar *d, [Manip m,]]
stock_enum i1, stock_enum i2=stock_NULL,
..., stock_enum i5 = stock_NULL) const;
template <class Manip>
stock_cus_value_list<Manip>
value_list([cchar *d, [Manip m,]] vector<bool> *i) const;
...( field_list equal_list)...
};

value_list() ,
<< ostream
.
field_list() , ,
, .
.
equal_list()
=. ,
. :
stock s("Dinner Roles",75,0.95,0.97,"1998-05-25");
cout << "Value List: " << s.comma_list() << endl;
cout << "Field List: " << s.field_list() << endl;
cout << "Equal List: " << s.equal_list() << endl;

:
Value List: 'Dinner Roles',75,0.95,0.97,'1998-05-25' Field List:
item,num,weight,price,date Equal List: item = 'Dinner Roles',num = 75,weight = 0.95,
price = 0.97,date = '1998-05-25'

. :
query << "insert into stock (" << s.field_list() ")
values " << s.value_list();

s stock.
SQLQuery::insert SQLQuery::replace (
Query::insert Query::replace),
:
query.insert(s);

s.table ,
.
"d".
, ",". "
AND " equal_list, . :
stock s2 = s;
s2.item = "6 Dinner Roles";
query << "UPDATE TABLE stock SET " << s2.equal_list()
<< " WHERE " << s.equal_list(" AND ");

:
UPDATE TABLE stock SET item = '6 Dinner Roles',num=75,weight = 0.95,
price = 0.97,date = '1998-05-25'

WHERE item = 'Dinner Roles' AND num = 75 AND


weight = 0.95 AND price = 0.97 AND date = '1998-05-25'

, "6 Dinner Roles"


"Dinner Roles".
SQLQuery::update (
Query::update) :
stock s2 = s;
s2.item = "6 Dinner Roles";
query.update(s,s2);

SQLQuery::insert, s.table ,
.
, c++
. ,
. value_list
equal_list escape, field_list do_nothing.
equal_list value, field
name.
,
. :
table_out << q.value_list("\ t",
mysql_escape) << endl;

, table_out.
,
. :
cout << q.value_list(false,false,true,true,false) << endl;
cout << q.value_list(stock_weight, stock_price) << endl;

:
0.95,0.97

bool form ,
, . :
cout << q.value_list(false,false,true,true) << endl;

.
list form , .
enum
, , item stock_item.

. :
query << "SELECT * FROM stock WHERE "
<< q.equal_list(" AND ",stock_weight,stock_price);

:
SELECT * FROM stock WHERE weight=0.95 AND price=0.97

stock, weight price,


q.
vector form ( ) ,
, , .
,
. a , a[0]
, a[1] . :
vector<bool> a;
a[0] = false;
a[1] = false;
a[2] = true;
a[3] = true;
a[4] = false;
query << "SELECT * FROM stock WHERE " <<
q.equal_list(" AND ", a);

,
.
3.7.8 sql_create_c_names

:
sql_create_c_names_5(stock, 1, 5, string, item, "item",
int, num, "quantity", double, weight,
"weight", double, price, "price"
MysqlDate, date, "shipment")

field_list equal_list ,
. :
stock s("Dinner Roles",75,0.95,0.97,"1998-05-25");
cout << "Field List: " << s.field_list() << endl;
cout << "Equal List: " << s.equal_list() << endl;

:
Field List: item,quantity,weight,price,shipment
Equal List: item = 'Dinner Roles',quantity = 75,weight = 0.95,
price = 0.97,shipment = '1998-05-25'

3.7.9 sql_create_c_names

:
sql_create_c_names_#(NAME, CMP, CNST, TYPE1, ITEM1, NAME1, ...
TYPE#, ITEM#, NAME#)

NAME1 . ,
sql_create_basic_c_order.
3.7.10 sql_create_c_order

sql_create_basic_c_order .
:
sql_create_c_order_#(NAME, CMP, CNST, TYPE1, ITEM1, ORDER1, ...
TYPE#, ITEM#, ORDER#)

, sql_create_basic_c_order.
3.7.11 sql_create_complete

.
:
sql_create_complete_#(NAME, CMP, CNST, TYPE1, ITEM1, NAME1, ORDER1, ...
TYPE#, ITEM#, NAME#, ORDER#)

, sql_create_c_order sql_create_c_names.
3.7.12


. SQLQuery::insert, replace
update. ,
, , NAME::table()
const char *:
stock::table() = "in_stock"

"in_stock" ,
.
3.7.13

, sql++pretty,
. :
sql++pretty < test.cc | less

3.7.14

:
. ,
pretty.pl , ,
.
3.7.15

25 .
, perl (custom.pl).
perl , .
C++.
, custom.pl .
, , (custom-macros.hh)
.
.
, ,

- .
3.8.
Mysql++ API Mysql
mysql_, Mysql mysql_.
, MYSQL_NO_SHORT_NAMES
mysql++.
. :

BadQuery
Connection
ResNSel
ResUse
Result
Field
Fields
ResIter


MysqlBadQuery
MysqlConnection
ResNSel
ResUse MysqlResUse
MysqlRes
MysqlField
MysqlFields
MysqlResIter

ResultIter
Row
MutableRow
FieldNames
Query
BadConversion
ColData
MutableColData
quote
quote_only
quote_double_only
escape
do_nothing
ignore
Date
Time
DateTime
Set
Null
null_type
null
NullisNull
NullisZero
NullisBlank

MysqlResIter
MysqlRow
MysqlMutableRow
MysqlFieldNames
MysqlQuery
MysqlBadConversion
MysqlColData
MysqlMutableColData
mysql_quote
mysql_quote_only
mysql_quote_double_only
mysql_escape
mysql_do_nothing
mysql_ignore
MysqDate
MysqlTime
MysqlDateTime
MysqlSet
MysqlNull
mysql_null_type
mysql_null
MysqlNullisNull
MysqlNullisZero
MysqlNullisBlank

3.9 - mysql C++


: Roland Haenel (rh@ginster.net). public domain.
.
C++,
mysql.
:

mysql ( Michael Widenius).


msql ( David Hughes).
postgres95 ( Postgres Group).

, mysql ,
.
mysql.

example.cc.
:
Database mysqld.
:

int Database::init()
,
- .
.
int Database::status();
. :
DB_CONNECTION_NONE, DB_CONNECTION_OK
DB_CONNECTION_BAD.
char Database::*errorMessage();
, ,
int Database::connect(char *host, char *port, char *db);
db host. ,
port .
void Database::disconnect();
.
int Database::reset();
.
DBResult *Database::exec(char *sqlFormat, ...);
void Database::exec(DBResult *res, char *sqlFormat, ...);
SQL.
DBResult ( ).
DBResult.
int DBResult::status();
, .
:

#define
#define
#define
#define
#define
#define

int DBResult::nrTuples();
( status() == DB_TUPLES_OK).
int DBResult::nrFields();
( status() == DB_TUPLES_OK).
char *DBResult::fieldName(int n);
n.
int DBResult::fieldSize(int n);
n.

DB_COMMAND_OK
DB_EMPTY_QUERY
DB_TUPLES_OK
DB_ERROR
DB_BAD_RESPONSE
DB_UNEXPECTED

0
1
2
5
6
7

//
//
//
//
//
//

OK:




int DBResult::fieldSize(char *name);


name.
void DBResult::seekTuple(int tuple);
tuple.
getTuple().
char **DBResult::getTuple();
. getTuple()[0]
..
char **DBResult::getTuple(int tuple);
. , ,
.
seekTuple()/getTuple().

3.10 MyDAO: - C++


v0.1 (19-Feb-2000). : Satish (spitfire@pn3.vsnl.net.in). : Feel
free to use/copy/modify/add bugs/find bugs, but keep the author informed.

C++ MySQL.
C++, Data Access Objects.
, Roland Hanel (MySQL C++)
Ed Carp (MyC). MyC C
.
. MyDAO ver 0.1.

dbconnect class: .
MySQL . :

bool Connected;
Connected true, MySQL .
MYSQL *DBase;
DBase MYSQL. ,
.

void dbconnect::Connect(char *host, char *port, char *uname, char*pwd);


MySQL,
, , .
, Connected true.
void dbconnect::Disconnect();
MySQL.

bool dbconnect::OpenDB(char *db);


db. , true.

:
dbconnect MyConnect;
char host[]="localhost";
char port[]="3306";
char name[]="satish";
char pwd[]="";
char db[]="orders";
MyConnect.Connect(host, port, name, pwd);
if (MyConnect.Connected) cout << "Connected" << endl;
else
{
cout << "Connection failed" << endl;
return;
}
if (!MyConnect.OpenDB(db)) {
cout << "Can not open selected database" << endl;
return;
}
else
{
cout << "Opened datbase: " << db << endl;
//
open recorset(s)...
//
Manipulate data...
}
MyConnect.Disconnect();

recordset class:
. .
:

char RecSource[MAX_RECSRC_LEN];
, .
SQL- SELECT, .
unsigned long int RecordCount;
.
unsigned long int AffectedRows;
Update, AddNew Delete.
.
bool EOR;
. True, .
bool BOR;
. True, .
: EOR BOR true, RecordCount=0.

void recordset::OpenRecordset(MYSQL *Structmysql, char *sql);


SQL- select.
void recordset::CloseRecordset();
. ,
, .
void recordset::MoveNext();
.
, .
void recordset::MovePrevious();
.
, .
void recordset::MoveFirst();
.
void recordset::MoveLast();
.
char* recordset::GetField(char *FName);
FName.
void recordset::SetField(char *FName, char *Value);
FName Value.
,
Update/AddNew.
void recordset::Edit();
SetField Update,
.
void recordset::AddNew();
, .
.
Update .
WHERE Update,
AddNew. AffectedRows
.
void rercordset::Update(char *Where);
,
Edit/AddNew. WHERE AddNew.
void recordset::Delete(char *Where);
, .
void recordset::Refresh();
, Update, , Refresh
. Update.
char* recordset::GetFieldN(int FNum);
GetField, ().
void recordset::SetFieldN(int FNum, char *Value)
SetField, ().

1:

//
dbconnect.
//
(customers)
//
.
recordset MySet;
char sql[]="SELECT * FROM customers";
MySet.OpenRecordset(MyConnect.DBase, sql);
if (MySet.EOR && MySet.BOR){
cout << "No records found" << endl;
return;
}
else
{
// Show number of records
cout << "No. of records: " << MySet.RecordCount << endl;
// Show all records
while (!MySet.EOR)
{
cout << MySet.GetField("or_id") << "\t";
cout << MySet.GetField("customers") << "\t";
cout << MySet.GetField("city") << endl;
MySet.MoveNext();
}
}

2:
//
.
MySet.AddNew();
MySet.SetField("cs_id", "7");
MySet.SetField("name", "Satish");
MySet.SetField("city", "Pune");
MySet.Update("");
// where !
MySet.Refresh();
// .

3:
//
.
MySet.Edit();
MySet.SetField("cs_id", "7");
MySet.SetField("name", "Suresh");
MySet.SetField("city", "Pune");
MySet.Update("or_id=7");
// where .
MySet.Refresh();
// .

4:
//
.
MySet.Delete("name='Suresh'");
MySet.Refresh();

5:

// .

//
. !
MySet.CloseRecordset();


(FindFirst, FindNext, FindPrevious, FindLast)

4. LUA
Lua
4.0
4.1
4.1.1 Lua?

Lua: http://www.lua.org/.
Lua ,
. , , , Lua
API,
Lua Lua C. , Lua
.
Lua ( ) Second Compaq
Award for Research and Development in Computer Science 1997.
Compaq Computer Brazil, the
Brazilian Ministry of Science and Technology the Brazilian Academy of Sciences.
Lua .
http://www.lua.org/uses.html.
Lua ( )
,
. Lua , .
Lua ,
,
. Lua ,
, ,
. Lua
.

: , ,
. : ,
.
Lua C, ANSI C
. , Lua
:
. ,
Lua, Lua,
C, Lua-.
C, Lua ,
,
, .
4.1.2

Lua
:

:
http://www.lua.org/
:
Brazil: http://www.lua.org/ftp/
Germany: http://ftp.gwdg.de/pub/languages/lua/
Germany: ftp://ftp.gwdg.de/pub/languages/lua/
Greece: ftp://ftp.ntua.gr/pub/lang/lua/
Japan:
ftp://ftp.u-aizu.ac.jp/pub/lang/lua/
Denmark: ftp://ftp.ucore.com/lua/dist
: http://ftp.chg.ru/pub/lang/lua/

Lua . , ,
: http://www.lua.org/home.html
4.1.3

Lua Waldemar Celes, Roberto Ierusalimschy Luiz


Henrique de Figueiredo. e-mail lua@tecgraf.pucrio.br.
, lua@tecgraf.puc-rio.br.
lua-l@tecgraf.pucrio.br.
, , ,
http://www.lua.org/mirrors.html.
Lua TeCGraf, the Computer Graphics Technology Group of PUC-Rio (the
Pontifical Catholic University of Rio de Janeiro in Brazil). TeCGraf

. ,
TeCGraf, Lua.
4.2
Lua .
lua_open
lua_close .

.
Lua- ,
, API
, Lua.
Lua .
, .
, nil (
, 4.4.8). ,
( 4.3).
Lua .
, .
:
chunk ::= {stat [`;']}

4.4.4.
BNF, {a} 0 a [a]
a, (a)+ a.
(chunk)
. chunk , ,
, .
.
Chunk .

. Lua
.
4.3
Lua dynamically typed language. ,
, . ,

. .
.
Lua: nil, number (), string (), function
(), userdata ( ) table (). Nil
nil, . Number
( ) ,
string . Lua 8- ,
8- ,
('\0'). 4.4.1. type ,
( 4.6.1).
(first-class values) Lua.
, ,
. Lua
, Lua, ,
C. : Lua
, C ,
Lua. tag ( 4.6.1).
userdata , C-
Lua-. void*
Lua,
. , ,
userdata. 4.4.8.
table , ,
, (
nil). , ,
, , , , ,
.. ,
Lua. (records), Lua .
, a.name
a["name"]. :
,
. t:f(x) t.f(t,x),
f t
( 4.4.5.9).
, , .
, . ,

. ,
, . 4.4.5.7.

nil, number string . , Lua


.
. , function
, Lua
C. , userdata table
, ( 4.4.8).
tag .
newtag. settag ,
( 4.6.1). userdata
C ( 4.5.7).
, ,
.
Lua ( 4.4.8).
4.4
, Lua.
4.4.1

Lua ,
, .
, ,
. ,
, . ,
. ,

, :
. ,
:
and
end
local

break
for
nil

do
function
not

else
elseif
if
in
or repeat until

return
then
while

Lua , : and
, And AND ( )
. ,
. , ,
, ( _INPUT)
.
.
(tokens):

~=
(

<=
)

>=
{

<
}

>
[

==
]

=
;

+
,

*
..

...


, C- : \a
(bell), \b (backspace), \f (form feed), \n (newline), \r (carriage return), \t (horizontal
tab), \v (vertical tab), \\ (backslash), \" (double quote), \' (single quote), \newline
( , , newline,
).
, \ddd, ddd
. Lua
8- , ,
\000.
[[ ... ]].
,
[[ ... ]] .
,
. , ASCII, :
1)
2)
3)

"alo\n123\""
'\97lo\10\04923"'
[[alo
123"]]

(--) .
, ,
#. Lua
Unix-.

.
. :
3

3.0

3.1416

314.16e-2

0.31416E1

4.4.2

Lua
. , ,
,
. , , , ,
. ,
,

. ,
.
, ,
format ( 4.6.2).
4.4.3

Lua . ,
, ,
, . ,
.
, ,
. , ,
nil.
( 4.4.4.2)
( 4.4.5.8).
4.4.4

Lua ,
Pascal C. ,
.
.
4.4.4.1

.
(chunk):
block ::= chunk

:
stat ::= do block end

, ()
. ,
.
4.4.4.2

Lua , .
,
.
:

stat ::= varlist1 `=' explist1


varlist1 ::= var {`,' var}


, . , :
i = 3
i, a[i] = 4, 20

a[3] 20, a[4] , i a[i]


, 4.
, , :
x, y = y, x

.
,
.
,
:
var ::= name

, :
var ::= varorfunc `[' exp1 `]'
varorfunc ::= var | functioncall

varorfunc , ,
exp1, .
var.NAME
var["NAME"]:
var ::= varorfunc `.' name

,
. , x=val,
x ,
setglobal("x",val), t[i]=val
settable_event(t,i,val). 4.4.8
(setglobal , settable_event
).
4.4.4.3

if, while repeat


:
stat ::= while exp1 do block end
stat ::= repeat block until exp1
stat ::= if exp1 then block {elseif exp1 then block} [else block] end

exp1
. , nil, , nil
.
return ,
chunk. ,
, return:
stat ::= return [explist1]

break , ,
:
stat ::= break

break (while, repeat for).


return break
.
, , , do return end
, return
.
4.4.4.4 For

for , .
for :
stat ::= for name `=' exp1 `,' exp1 [`,' exp1] do block end

for, :
for var = e1 ,e2, e3 do block end

:
do
local var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3)
if not (var and _limit and _step) then error() end
while (_step>0 and var<=_limit) or
(_step<=0 and var>=_limit) do
block
var = var+_step
end

end

sep=0pt
_step .
.
, var .
(step) , step 1.
limit step , .
var :
for.
break, for.
, .
_limit

for (index,value) .
:
stat ::= for name `,' name in exp1 do block end

for, :
for index, value in exp do block end

:
do
local _t = exp
local index, value = next(t, nil)
while index do
block
index, value = next(t, index)
end
end

sep=0pt
_t .
.
, index .
, _t .
index var :
for.
break, for.
index value,
.
, , ,
.
, for.

4.4.4.5

- ,
:
stat ::= functioncall

.
4.4.5.8.
4.4.4.6

- .
:
stat ::= local declist [init]
declist ::= name {`,' name}
init ::= `=' explist1

,
. nil.
hunk ,
.
()
. , local print=print
, print,
.
4.4.5
4.4.5.1

Lua :
exp
exp
exp
exp
exp
exp
exp
exp
exp

::=
::=
::=
::=
::=
::=
::=
::=
::=

`(' exp `)'


nil
number
literal
var
upvalue
function
functioncall
tableconstructor

x getglobal("x"),
t[i]
gettable_event(t,i). 4.4.8,
(getglobal ).

exp1 , , ,
:
exp1 ::= exp

4.4.5.2

Lua : +
(), - (), * (), / (), ^ ( ),
- ( ). ,
, ( ,
4.4.2),
. .
.
, (
4.6.3).
4.4.5.3

Lua:
==

~=

<

>

<=

>=

nil , ( nil)
.
(==) . ,
nil. .
. , userdata,
, ,
. ~= (==).
4.4.2 .
, "0"==0 false, t[0] t["0"]
.
. ,
. , ,
, .
lt ( 4.4.8).
4.4.5.4

Lua:
and

or

not

, nil
false (), (true).
and nil, nil,
. or ,
nil, .
and or ,
. Lua,
. :
x = x or v

:
if x == nil then x = v end

x v, x .
:
x = a and b or c

x=(a and b) or c. :
if a then x = b else x = c end

, b nil.
4.4.5.5

Lua (`..').
,
4.4.2. concat .
4.4.5.6

Lua .
:
and
<
..
+
*
not
^

or
>

<=

>=

~=

==

/
- (unary)

, ,
.
( .. +),
. ,

,
.
4.4.5.7

, :
, .
,
( ).
:
tableconstructor ::= `{' fieldlist `}'
fieldlist ::= lfieldlist|ffieldlist|lfieldlist `;'
ffieldlist|ffieldlist `;' lfieldlist
lfieldlist ::= [lfieldlist1]
ffieldlist ::= [ffieldlist1]

lfieldlist1 , :
lfieldlist1 ::= exp {`,' exp} [`,']

,
1 ( 0!). , :
a = {"v1", "v2", 34}

:
do
local temp = {}
temp[1] = "v1"
temp[2] = "v2"
temp[3] = 34
a = temp
end

ffieldlist1 :
ffieldlist1 ::= ffield {`,' ffield} [`,']
ffield ::= `[' exp `]' `=' exp | name `=' exp

:
a = {[f(k)] = g(y), x = 1, y = 3, [0] = b+c}

:
do
local temp = {}
temp[f(k)] = g(y)
temp.x = 1
-- or temp["x"] = 1
temp.y = 3
-- or temp["y"] = 3
temp[0] = b+c
a = temp
end

, {x=1, y=4}
{["x"]=1, ["y"]=4}.

, .
, :
x
x
x
x

=
=
=
=

{;}
{"a", "b",}
{type="list"; "a", "b"}
{f(0), f(1), f(2),; n=3,}

4.4.5.8

Lua :
functioncall ::= varorfunc args

varorfunc. function,
. function ,
varorfunc
. 4.4.8.

functioncall ::= varorfunc `:' name args

, methods. v:name(...)
v.name(v, ...), , v
. :
args ::=
args ::=
args ::=
explist1

`(' [explist1] `)'


tableconstructor
literal
::= {exp1 `,'} exp

. f{...}
f({...}),
. f'...' (f"..."
f[[...]]) f('...'),
.
, ,
, .
, 0,
. ,
(
exp1), 1,
, .
, (

exp), .
, , (
) ,
return. :
f()
g(f(), x)
g(x, f())
a,b,c = f(), x
a,b,c = x, f()
a,b,c = f()
return f()
return x,y,f()

---------

0
f() 1
g x , f()
f() 1 ( c nil)
f() 2
f() 3
, f()
a, b , f()

4.4.5.9

:
function ::= function `(' [parlist1] `)' block end
stat ::= function funcname `(' [parlist1] `)' block end
funcname ::= name | name `.' name | name `:' name

function f () ... end


f = function () ... end


function v.f () ... end


v.f = function () ... end

,
function. Lua chunk,
. , , Lua
(upvalues)
, . (
) .

.
,
:
parlist1 ::= `...'
parlist1 ::= name {`,' name} [`,' `...']

,
, vararg-,
(`...') . vararg
, ,
arg. arg n ,
,
1, 2, ..., n.
, :
function f(a, b) end
function g(a, b, ...) end
function r() return 1,2,3 end

f(3)
f(3, 4)
f(3, 4, 5)
f(r(), 10)
f(r())
g(3)
g(3, 4)
g(3, 4, 5, 8)
g(5, r())

a=3,
a=3,
a=3,
a=1,
a=1,
a=3,
a=3,
a=3,
a=5,

b=nil
b=4
b=4
b=10
b=2
b=nil, arg={n=0}
b=4, arg={n=0}
b=4, arg={5, 8; n=2}
b=1, arg={2, 3; n=2}

, return.
, return,
.

funcname ::= name `:' name

, ,
self .

function v:f (...) ... end


v.f = function (self, ...) ... end

,
self.
4.4.6 Upvalues


( ), ,
.
,
, . ,

, upvalues, :
upvalue ::= `%' name

upvalue , ,
, . , upvalue,
, , ,
.
, , upvalue , (
upvalue) ,
. upvalues

, .
:
a,b,c = 1,2,3
--
local d
function f (x)
local b = {} -- x b f, b b
local g = function (a)
local y
-- a y g
p = a
-- OK, a
p = c
-- OK, c
p = b
-- ERROR:
p = %b
-- OK, b ( f)
%b = 3
-- ERROR: upvalue
%b.x = 3
-- OK,
p = %c
-- OK, c
p = %y
-- ERROR: `y' , `g'
p = %d
-- ERROR: `d' , `g'
end
-- g
end
-- f

4.4.7

Lua , Lua C-
, Lua-. ,
Lua- ,
_ERRORMESSAGE
(lua_dofile, lua_dostring, lua_dobuffer lua_call) ,
.


. , Lua
_ERRORMESSAGE. , , Lua
_ERRORMESSAGE.
(LUA_ERRMEM).
lua.h,
4.5.8.
_ERRORMESSAGE: , .
: _ALERT,
stderr. -
_ERRORMESSAGE ,
, .
Lua- , error (
4.6.1). Lua- ,
call ( 4.6.1).
4.4.8

Lua , ,
. ,
Lua,
Lua .
(event).
.
settagmethod , (tag, event).
, ( ),
() nil,
. settagmethod
. - gettagmethod
, .
,
.
Lua, .
, , ,
. , ,
:
, . ,
(rawget, tonumber, call ..), 4.6.1.
``add'':
, + .

getbinmethod , Lua
. Lua .
, Lua .
, Lua 0.
function getbinmethod (op1, op2, event)
return gettagmethod(tag(op1), event) or
gettagmethod(tag(op2), event) or gettagmethod(0, event)
end

, ``add'' :
function add_event (op1, op2)
local o1, o2 = tonumber(op1), tonumber(op2)
if o1 and o2 then -- both operands are numeric
return o1+o2 -- '+' here is the primitive 'add'
else -- at least one of the operands is not numeric
local tm = getbinmethod(op1, op2, "add")
if tm then
-- call the method with both operands and an extra
-- argument with the event name
return tm(op1, op2, "add")
else -- no tag method available: default behavior
error("unexpected type at arithmetic operation")
end
end
end

``sub'':
, - .
``add''.
``mul'':
, * .
``add''.
``div'':
, / .
``add''.
``pow'':
, ^ ( )
.
function pow_event (op1, op2)
local tm = getbinmethod(op1, op2, "pow")
if tm then
-- call the method with both operands and an extra
-- argument with the event name
return tm(op1, op2, "pow")
else -- no tag method available: default behavior
error("unexpected type at arithmetic operation")
end
end

``unm'':
, -
.

function unm_event (op)


local o = tonumber(op)
if o then -- operand is numeric
return -o -- '-' here is the primitive 'unm'
else -- the operand is not numeric.
-- Try to get a tag method from the operand;
-- if it does not have one, try a "global" one (tag 0)
local tm = gettagmethod(tag(op), "unm") or
gettagmethod(0, "unm")
if tm then
-- call the method with the operand, nil, and an extra
-- argument with the event name
return tm(op, nil, "unm")
else -- no tag method available: default behavior
error("unexpected type at arithmetic operation")
end
end
end

``lt'':
,
. <.
function lt_event (op1, op2)
if type(op1) == "number" and type(op2) == "number" then
return op1 < op2
-- numeric comparison
elseif type(op1) == "string" and type(op2) == "string" then
return op1 < op2
-- lexicographic comparison
else local tm = getbinmethod(op1, op2, "lt")
if tm then return tm(op1, op2, "lt")
else error("unexpected type at comparison");
end
end
end


:
a>b
a<=b
a>=b

<=>
<=>
<=>

b<a
not (b<a)
not (a<b)

``concat'':
, .
function concat_event (op1, op2)
if (type(op1) == "string" or type(op1) == "number") and
(type(op2) == "string" or type(op2) == "number") then
return op1..op2 -- primitive string concatenation
else local tm = getbinmethod(op1, op2, "concat")
if tm then return tm(op1, op2, "concat")
else error("unexpected type for concatenation")
end
end
end

``index'':
, Lua ,
.
``getglobal'':

, Lua .
nil ,
newtag. ,
.
function getglobal (varname)
-- access the table of globals
local value = rawget(globals(), varname)
local tm = gettagmethod(tag(value), "getglobal")
if not tm then return value
else return tm(varname, value)
end
end

getglobal .
``setglobal'':
, Lua .
, , userdata
.
function setglobal (varname, newvalue)
local oldvalue = rawget(globals(), varname)
local tm = gettagmethod(tag(oldvalue), "setglobal")
if not tm then rawset(globals(), varname, newvalue)
else tm(varname, oldvalue, newvalue)
end
end

setglobal .
``gettable'':
, Lua .

.
function gettable_event (table, index)
local tm = gettagmethod(tag(table), "gettable")
if tm then return tm(table, index)
elseif type(table) ~= "table" then
error("indexed expression not a table");
else local v = rawget(table, index)
tm = gettagmethod(tag(table), "index")
if v == nil and tm then return tm(table, index)
else return v
end
end
end

``settable'':
, Lua .

.
function settable_event (table, index, value)
local tm = gettagmethod(tag(table), "settable")
if tm then tm(table, index, value)
elseif type(table) ~= "table"
then error("indexed expression not a table")
else rawset(table, index, value)

end
end

``function'':
, Lua .
function function_event (func, ...)
if type(func) == "function" then return call(func, arg)
else local tm = gettagmethod(tag(func), "function")
if tm then for i=arg.n,1,-1 do arg[i+1] = arg[i]
end
arg.n = arg.n+1
arg[1] = func
return call(tm, arg)
else error("call expression not a function")
end
end
end

``gc'':
, Lua userdata.
C, userdata
. userdata,
, Lua
:
function gc_event (obj)
local tm = gettagmethod(tag(obj), "gc")
if tm then tm(obj)
end
end

userdata ,
, , ,
, . ,
Lua gc_event(nil).
4.5 API
API Lua, C,
, Lua. API,
lua.h.
"", API
.
.
4.5.1

Lua :
. Lua (
, , ..)

lua_State.
( lua_open).
API, :
lua_State *lua_open (int stacksize);

: .
,
,
. 20
. ,
, 100 .
stacksize 0,
1024.
, lua_open, :
void lua_close (lua_State *L);

Lua (
, )
, .
, ,
. ,

, .
lua_open Lua API
.
4.5.2

Lua (stack), C.
Lua (nil, , ).
API
. ,
:
( 1, 0, C).
. , n ,
1 ( , ,
), n . -1
( , ), -n
. , , 1
( , 1 <= abs(index) <= top).

:
int lua_gettop (lua_State *L);

, 1, lua_gettop
(0 ).
Lua API,
.
int lua_stackspace (lua_State *L);

. , Lua C,
, LUA_MINSTACK .
LUA_MINSTACK lua.h 16,
, ,
.

. .
:
(index < 0 && abs(index) <= top) ||
(index > 0 && index <= top + stackspace)

, 0 .
4.5.3

API :
void
void
void
void

lua_settop(lua_State *L, int index);


lua_pushvalue(lua_State *L, int index);
lua_remove(lua_State *L, int index);
lua_insert(lua_State *L, int index);

0
. ,
, nil. index 0,
. , API:
lua_settop

#define lua_pop(L,n) lua_settop(L, -(n)-1)

n .
. lua_remove
, ,
lua_pushvalue

. lua_insert
, .
. ,
( ) 10 20 30 40 50:
lua_pushvalue(L, 3)
lua_pushvalue(L, -1)
lua_remove(L, -3)
lua_remove(L, 6)
lua_insert(L, 1)
lua_insert(L, -1)
lua_settop(L, -3)
lua_settop(L, 6)

-->
-->
-->
-->
-->
-->
-->
-->

10
10
10
10
30
30
30
30

20
20
20
20
10
10
10
10

30
30
30
30
20
20
20
20

40
40
40
40
30
30

50 30
50 30 30
30 30
30
40
40 ( )

nil nil nil

4.5.4

, :
int
int
int
int
int
int
int
int
int

lua_type(lua_State *L, int index);


lua_tag(lua_State *L, int index);
lua_isnil(lua_State *L, int index);
lua_isnumber(lua_State *L, int index);
lua_isstring(lua_State *L, int index);
lua_istable(lua_State *L, int index);
lua_isfunction(lua_State *L, int index);
lua_iscfunction(lua_State *L, int index);
lua_isuserdata(lua_State *L, int index);

.
lua_type , :
LUA_TNIL, LUA_TNUMBER, LUA_TSTRING, LUA_TTABLE, LUA_TFUNCTION, LUA_TUSERDATA.
( , ), lua_type
LUA_TNONE.

:
const char *lua_typename(lua_State *L, int t);

t , lua_type. ,
lua_typename: "nil", "number", "string", "table", "function", "userdata" "no
value",
lua_tag

LUA_NOTAG .

lua_is* 1, , 0
. 0 .
lua_isnumber . lua_isstring
lua_isfunction Lua C.
Lua C, lua_iscfunction.

,
lua_type.
API , :
int lua_equal(lua_State *L, int index1, int index2);
int lua_lessthan(lua_State *L, int index1, int index2);

Lua. , lua_lessthan
lt_event. 0,
.
C,
:
double lua_tonumber(lua_State *L, int index);
const char *lua_tostring(lua_State *L, int index);
size_t lua_strlen(lua_State *L, int index);
lua_CFunction lua_tocfunction(lua_State *L, int index);
void *lua_touserdata(lua_State *L, int index);

.
, ,
.

. ,
( 4.4.2). lua_tonumber 0.
lua_tonumber

Lua (const char*).


, NULL.
Lua-.
('\0') ( C),
. , ,
lua_strlen, . , Lua
, , ,
lua_tostring, ,
.
lua_tostring

C.
C, lua_tocfunction NULL.
lua_CFunction 4.5.13.
lua_tocfunction

void*.
userdata, lua_touserdata NULL.
lua_touserdata

4.5.5

API , C :
void
void
void
void
void
void

lua_pushnumber(lua_State *L, double n);


lua_pushlstring(lua_State *L, const char *s, size_t len);
lua_pushstring(lua_State *L, const char *s);
lua_pushusertag(lua_State *L, void *u, int tag);
lua_pushnil(lua_State *L);
lua_pushcfunction(lua_State *L, lua_CFunction f);

C,
Lua, . , lua_pushlstring
lua_pushstring . lua_pushstring
, C- ( ,
, ),
lua_pushlstring,
.
4.5.6

Lua , .
, Lua ,
. , Lua
: 10% .
, Lua ,
,
( , Lua).
, .

:
int lua_getgccount (lua_State *L);
int lua_getgcthreshold (lua_State *L);

.
:
void

lua_setgcthreshold (lua_State *L, int newthreshold);

newthreshold .
, Lua .
, , Lua .
.
,
nil,
( , Lua
).

4.5.7 Userdata

userdata , lua_pushusertag
userdata. Lua userdata (void*)
, . userdata
. , LUA_ANYTAG , Lua
userdata , .
userdata ,
, 0.
Userdata ,
. :
int lua_newtag (lua_State *L);

lua_settag ( ,
):
void lua_settag (lua_State *L, int tag);

userdata , ,
lua_newtag.
4.5.8 Lua-

Lua-chunk, ,
:
int lua_dofile(lua_State *L, const char *filename);
int lua_dostring(lua_State *L, const char *string);
int lua_dobuffer(lua_State *L, const char *buff, size_t size,
const char *name);

0 ,
, :

LUA_ERRRUN: chunk.
LUA_ERRSYNTAX: .
LUA_ERRMEM: . , Lua
_ERRORMESSAGE ( 4.4.7).
LUA_ERRERR: _ERRORMESSAGE. Lua
_ERRORMESSAGE , .
LUA_ERRFILE: ( lua_dofile).
errno, strerror perror,

, .
lua.h.

lua_dofile NULL,
stdin. lua_dofile lua_dobuffer
. ,
, . lua_dostring
, .
lua_dobuffer chunk,
. name NULL,
Lua chunk.
,
. ; Lua
, , ,
.
, ,
lua_stackspace,
( ). ,
,
:
{
int oldtop = lua_gettop(L);
lua_dofile(L, filename);
lua_settop(L, oldtop);
}

4.5.9 Lua

Lua, :
void lua_getglobal (lua_State *L, const char *varname);

. Lua
getglobal.
, ,
lua_rawget .
:
void lua_setglobal (lua_State *L, const char *varname);

, .
Lua setglobal.
,
, lua_rawset
( ).

Lua-.
:
void lua_getglobals (lua_State *L);

() .
, :
void lua_setglobals (lua_State *L);

, , .
4.5.10 Lua

Lua- API.
, - .

void lua_gettable (lua_State *L, int index);

index . lua_gettable
( ) . Lua
gettable.
, , ,
,
void lua_rawget (lua_State *L, int index);

, - ,
( !),
:
void lua_settable (lua_State *L, int index);

index . lua_settable
. Lua,
settable. ,
, raw-:
void lua_rawset (lua_State *L, int index);

,
void lua_newtable (lua_State *L);

, , .
4.5.11

API , Lua ,
, :
void lua_rawgeti(lua_State *L, int index, int n);
void lua_rawseti(lua_State *L, int index, int n);
int lua_getn(lua_State *L, int index);

lua_rawgeti

index .

index
.
lua_rawseti

index.
n , ,
non-nil .
lua_getn

4.5.12 Lua

, Lua ( C, Lua),
. ,
: , , , , ,
,
. , :
int lua_call (lua_State *L, int nargs, int nresults);

, lua_dostring
( 4.5.8). , ,
, :
void lua_rawcall(lua_State *L, int nargs, int nresults);

nargs , .
,
.
nresults, nresults LUA_MULTRET.
.
( ),
.
,
Lua:

a,b = f("how", t.x, 4)

Here it is in C:
/* `t' ( ) */
lua_getglobal(L, "t");
/* , */
lua_getglobal(L, "f");
/* 1- */
lua_pushstring(L, "how");
/* `x' */
lua_pushstring(L, "x");
/* t.x (2- ) */
lua_gettable(L, -4);
/* 3- */
lua_pushnumber(L, 4);
/* 3 2 */
lua_call(L, 3, 2);
/* `b' */
lua_setglobal(L, "b");
/* `a' */
lua_setglobal(L, "a");
/* `t' */
lua_pop(L, 1);

, :
. .
Lua C.
Lua, :
void lua_error (lua_State *L, const char *message);

. lua_error
C, Lua, Lua
, Lua.
exit(EXIT_FAILURE). ,
message _ERRORMESSAGE.
message NULL, _ERRORMESSAGE .

void lua_settagmethod (lua_State *L, int tag, const char *event);

, .
. ()

void lua_gettagmethod(lua_State *L, int tag, const char *event);

:
int lua_copytagmethods (lua_State *L, int tagto, int tagfrom);

tagto.
:
int lua_next (lua_State *L, int index);

index , .
"-" (
). , 0 (
).
:
lua_pushnil(L); /* first key */
while (lua_next(L, t) != 0) {
/* `key' is at index -2 and `value' at index -1 */
printf("%s - %s\n", lua_typename(L, lua_type(L, -2)),
lua_typename(L, lua_type(L, -1)));
lua_pop(L, 1); /* removes `value'; keeps `index' for next iteration */
}

void lua_concat (lua_State *L, int n);

n ,
. n 2.
Lua
4.5.13 C

C Lua, :
#define lua_register(L, n, f) (lua_pushcfunction(L,f),lua_setglobal(L,n))
/* const char *n;
*/
/* lua_CFunction f; */

, Lua,
. lua_CFunction,
;
typedef int (*lua_CFunction) (lua_State *L);

,
, Lua-.
Lua, C
, , :
C Lua , (
). Lua, C
.
Lua, C, Lua, .

,
, :
static int foo (lua_State *L) {
int n = lua_gettop(L);
/* number of arguments */
double sum = 0;
int i;
for (i = 1; i <= n; i++) {
if (!lua_isnumber(L, i))
lua_error(L, "incorrect argument to function `average'");
sum += lua_tonumber(L, i);
}
lua_pushnumber(L, sum/n);
/* */
lua_pushnumber(L, sum);
/* */
return 2;
/* */
}

Lua average :
lua_register(L, "average", foo);

C , upvalues,
C;
, , .
upvalues C, .

void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);

, C n ,
upvalues ( upvalues ).
, lua_pushcfunction lua_pushcclosure
n 0. , , C , upvalues
, ,
. ,
. i-th upvalue
i-(n+1), n upvalues.
C
lbaselib.c, liolib.c, lmathlib.c lstrlib.c Lua.
4.5.14 Lua-

C- Lua
C, . , ,
:
int lua_ref(lua_State *L, int lock);
int lua_getref(lua_State *L, int ref);

void lua_unref(lua_State *L, int ref);

,
. nil LUA_REFNIL. lua.h
LUA_NOREF, .
lock 0, : ,
.
.
lua_ref

, C, lua_getref
; , lua_getref 0 (
).
, lua_unref.
4.5.15

Lua LUA_REFREGISTRY.
:
#define lua_getregistry(L) lua_getref(L, LUA_REFREGISTRY)

C-
. C- ,
, .
4.6
,
API. ,
, C-.
, Lua :

.
.
(sin, log ,,).
( ).

, C-
lua_baselibopen, lua_strlibopen, lua_mathlibopen lua_iolibopen,
lualib.h.
4.6.1

Lua.
,
, , -
. ,
_ERRORMESSAGE Lua .
_ALERT (message)

stderr. Lua
, _ALERT.
, ,
, (,
stderr).
assert (v [, message])

assertion failed!, v nil.


Lua:
function assert(v, m)
if not v then m = m or ""
error("assertion failed!
end
end

" .. m)

call (func, arg [, mode [, errhandler]])

func , arg.

func(arg[1], arg[2], ..., arg[n])

n getn(arg). func
call.
, func,
. mode "x", .
call ,
, . ,
nil, (
).
errhandler , _ERRORMESSAGE
errhandler func. ,
errhandler nil,
.
collectgarbage ([limit])

( Kbytes).
, , Lua
. limit ,
( ).
copytagmethods (tagto, tagfrom)

, tagto.
dofile (filename)

,
Lua- . ,
dofile (stdin).
, dofile nil. , ,
-nil, .
, .
dostring (string [, chunkname])

Lua. ,
dostring nil. , ,
-nil, .
chunkname ,
.
error (message)


( C: lua_dofile, lua_dostring, lua_dobuffer lua_callfunction,
Lua: dofile, dostring call ). message nil,
. error .
foreach (table, func)

func table.
,
. -nil,
, foreach.
Lua :
function foreach (t, f)
for i, v in t do
local res = f(i, v)
if res then return res end
end
end

foreach , t .

foreachi (table, func)

func table.

. , 1 n,
n getn(table).
-nil, ,
foreachi. Lua
:
function foreachi (t, f)
for i=1,getn(t) do
local res = f(i, t[i])
if res then return res end
end
end

getglobal (name)


getglobal. 4.4.8 . name
.
getn (table)

, . n
, .
-nil .
Lua :
function getn (t)
if type(t.n) == "number" then return t.n end
local max = 0
for i, _ in t do
if type(i) == "number" and i>max then max=i end
end
return max
end

gettagmethod (tag, event)

(tag, event).
, gc.
C-.
globals ([table])

. table
, .

newtag ()

.
next (table, [index])

. : ,
. next
, . nil,
next .
nil , next nil.
, nil.
Lua :
, , nil.
, next -nil. ,
, .
, foreachi.
next , .
print (e1, e2, ...)

, , ,
tostring.
, ,
.
rawget (table, index)

table[index] ,
. table, index
, nil.
rawset (table, index, value)

table[index] value ,
. table , index
, nil, value Lua.
setglobal (name, value)

,
setglobal.
4.4.8.
settag (t, tag)

. (tag) ,
newtag. settag ().
userdata Lua.
settagmethod (tag, event, newmethod)

(tag, event)
. newmethod nil, settagmethod
.
, gc.
C-.
sort(table [, comp])

, table[1]
table[n], n getn(table).
comp , ,
( , nil), ,
(, not comp(a[i+1], a[i]) ).
comp , < Lua.
( , ,
).
tag (v)

Lua .
().
tonumber (e [, base])

. ,
, tonumber , nil.
, .
2 36 . ,
10, A ( ) 10, B
11 Z, 35. 10
( ) ,
. .
tostring (e)


. , ,
format.

tinsert (table [, pos] , value)

value pos ,
.
pos n+1, n getn(table) ,
tinsert(t,x) x t.
n , n+1.
Lua, , (
):
function tinsert (t, ...)
local pos, value
local n = getn(t)
if arg.n == 1 then pos, value = n+1, arg[1]
else pos, value = arg[1], arg[2]
end
t.n = n+1;
for i=n,pos,-1 do
t[i+1] = t[i]
end
t[pos] = value
end

tremove (table [, pos])

table pos,
, .
. pos n, n
getn(table), tremove(t)
t. n
n-1.
Lua, ,
( ):
function tremove (t, pos)
local n = getn(t)
if n<=0 then
return
end
pos = pos or n
local value = t[pos]
for i=pos,n-1 do
t[i] = t[i+1]
end
t[n] = nil
t.n = n-1
return value
end

type (v)

Lua . ,
, . :
"nil" (, nil!), "number", "string", "table", "function"
"userdata".
4.6.2 Lua


, .
Lua, 1 ( 0, C!).
, ,
, . ,
-1 .
strbyte (s [, i])

i- s. i ,
1. i .
.
strchar (i1, i2, ...)

0 . ,
,
, .
.
strfind (s, pattern [, init [, plain]])

pattern s. , strfind
s, ,
nil. ( gsub ),
.
init , :
1, .
plain ,
pattern,
. , plain,
init.
strlen (s)

. ("") 0.
, "a\000b\000c" 5
.

strlower (s)

,
. .
, , .
strrep (s, n)

, n s.
strsub (s, i [, j])

, s, i
j. i j , j ,
-1 ( ). , strsub(s,1,j)
s j, strsub(s, -i) s
i.
strupper (s)

,
. .
, .
format (formatstring, e1, e2, ...)


, (
). ,
printf C. ,
*, l, L, n, p h , q.
q , ,
Lua . ,
.
,
format('%q', 'a string with "quotes" and \n new line')

:
"a string with \"quotes\" and \
new line"


. %
%d$, d [1,9],
. , format("%2$d -> %1$03d",
1, 34) "34 -> 001".
, .

c, d, E, e, f, g, G, i, o, u, X x ,
q s . * ,
. , "%*g"
"%"...--..."g".
, , %s,
. %q
.
gsub (s, pat, repl [, n])

s, pat
, repl. gsub ,
, .
repl , .
repl %n n 1 9 n-
.
repl , ,
, ,
. , ,
, ,
.
n .
, n 1, pat .
:
x = gsub("hello world", "(%w+)", "%1 %1")
--> x="hello hello world world"
x = gsub("hello world", "(%w+)", "%1 %1", 1)
--> x="hello hello world"
x = gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
--> x="world hello Lua from"
x = gsub("home = $HOME, user = $USER", "%$(%w+)", getenv)
--> x="home = /home/roberto, user = roberto" (for instance)
x = gsub("4+5 = $return 4+5$", "%$(.-)%$", dostring)
--> x="4+5 = 9"
local t = {name="lua", version="4.0"}
x = gsub("$name - $version", "%$(%w+)", function (v) return %t[v] end)
--> x="lua - 4.0"
t = {n=0}
gsub("first second word", "(%w+)", function (w) tinsert(%t, w) end)
--> t={"first", "second", "word"; n=3}

, .
:
x
x : ^$()%.[]*+-?.
x.
. ()
%a

.
.

%c
%d

.
.

%l
%p

.
.

%s
%u

.
.

%w
%x

- .
.

%z
%x

0.

x - .
x. .
, (
!) %, .
[char-set]
, charset. ,
(-). %x, ,
char-set. char-set
. , [%w_] ( [_%w])
- , [0-7]
, [0-7%l%-]
.
.
, , [%a-z] [a-%%]
.
[^char-set]

char-set, char-set
.
, (%a, %c, ...),
. , %S
.
, .. . ,
[a-z] %l.
.
:

,
.
, *, 0
.

.
, +, 1
.

.
, -,
0 . *,

.
, ?, 0
1 .
%n, n 1 9. , n-
.
%bxy, x y .
, x, y,
x y. , , ,
+1 x -1 y, y y,
0. , %b()
.

.
(^) . $
.

^ $
.
:

, ,
. ,
, ,
.
. , "(a*(.)%w(%s*))",
"a*(.)%w(%s*)" (, ,
1), . 2, ,
%s*, , 3.
. %z.
4.6.3


C. ,
^, x^y, x^y.
:
abs
max

acos
min

asin
mod

atan
rad

atan2
sin

ceil
sqrt

cos
tan

deg
frexp

exp
ldexp

floor
random

log log10
randomseed

PI.
C-, ,
, .
deg rad ,
.
max .
min . 1, 2
.
random randomseed
, ANSI C (
rand srand).
. random
[0,1).
n, random [1,n].
l u, random
[l,u]. .
4.6.4 -

- Lua ,
.
Lua, _INPUT _OUTPUT. _STDIN,
_STDOUT _STDERR stdin, stdout
stderr. Initially, _INPUT=_STDIN _OUTPUT=_STDOUT.
userdata,
(FILE*) , - (I/O).
, I/O nil
, nil, .
openfile (filename, mode)

, mode.
, , nil ,
. _INPUT _OUTPUT.
mode :
r
.
w
.
a
.
r+
, .
w+
, .
a+
, ,
.
mode b, ,
. ,
C fopen.
closefile (handle)

. _INPUT _OUTPUT.
readfrom (filename)

.
, ,
_INPUT . input.

, _INPUT stdin
_INPUT. - , nil
.
filename |,
popen. . , ,
,
.
writeto (filename)

.
, ,
_OUTPUT . .
, ,
. ,
_OUTPUT stdout _OUTPUT.
nil , .
filename |,
popen. . , ,
,
.
appendto (filename)

, filename
_OUTPUT. writeto,
, , ,
. , nil ,
.
remove (filename)

. , nil
.
rename (name1, name2)

name1 name2. ,
nil .
flush ([filehandle])

. filehandle
, flush .
, nil .

seek (filehandle [, whence] [, offset])

, ,
, offset , whence
:
set
0 ( ).
cur
.
end
.
seek ,
. , nil
, .
whence cur, offset 0. ,
seek(file) ,
. seek(file, "set") (
0), seek(file, "end")
.
tmpname ()

,
. ,
.
read ([filehandle,] format1, ...)

_INPUT filehandle, ,
, , . ,
nil,
. ,
,
.
:
*n
. ,
.
*l
( ) nil .
.
*a

, . ,
.
*w
(
. . ,
,
. nil.

nil
.
write ([filehandle, ] value1, ...)

_OUTPUT filehandle,
. .
, tostring format write.
, nil .
4.6.5
clock ()

CPU, (
).
date ([format])

, ,
format. ,
ANSI C strftime. ,
,
.
execute (command)

C system. command,
.
, .
exit ([code])

C- exit code.
code: .
getenv (varname)

varname nil,
.
setlocale (locale [, category])

ANSI C setlocale. locale


, , category
, : "all", "collate", "ctype",
"monetary", "numeric" "time", : "all".
nil,
.
4.7
Lua . ,
, ,
,
,
.
luadebug.h.
4.7.1

,
:
int lua_getstack (lua_State *L, int level, lua_Debug *ar);

lua_Debug
, . 0
, n+1 , n.
lua_getstack 1, ,
, 0.
lua_Debug ,
:
typedef struct lua_Debug {
const char *event;
/* "call", "return" */
int currentline;
/* (l) */
const char *name;
/* (n) */
const char *namewhat;
/* (n) , , */
int nups;
/* (u) upvalues */
int linedefined;
/* (S) */
const char *what;
/* (S) "Lua" , "C" , Lua "main" */
const char *source;
/* (S) */
char short_src[LUA_IDSIZE]; /* (S) */
/* private part */

...
} lua_Debug;


. lua_Debug ,
:
lua_getstack

int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);

0 (, what).
what ar,
, lua_Debug:
S (source), linedefined what, l
(currentline) . , f
, .
, (
), what
>. , , f ,
:
lua_Debug ar;
lua_getglobal(L, "f");
lua_getinfo(L, ">S", &ar);
printf("%d\n", ar.linedefined);

lua_Debug :
source
, source
, , source @,
.
short_src
source,
.
linedefined
, .
what
"Lua", Lua, "C", C "main",
chunk.
currentline
, .
, currentline -1.
name
. Lua
, .
,
.
lua_getinfo ,
.

, name .
, name
. ,
, name NULL.
namewhat
. ,
namewhat "global". , namewhat "tagmethod", namewhat "" ( ).
nups
upvalues .
4.7.2

luadebug.h :
1
.

.
const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);
const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);

ar ,
lua_getstack
. lua_getlocal (n),
. lua_setlocal
,
. NULL . ,
, .
,
:
int listvars (lua_State *L, int level) {
lua_Debug ar;
int i = 1;
const char *name;
if (lua_getstack(L, level, &ar) == 0) return 0;
/* failure: no such level in the stack */
while ((name = lua_getlocal(L, &ar, i++)) != NULL) {
printf("%s\n", name);
lua_pop(L, 1); /* remove variable value */
}
return 1;
}

4.7.3

Lua- : call
line. :
typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);

:
lua_Hook lua_setcallhook (lua_State *L, lua_Hook func);
lua_Hook lua_setlinehook (lua_State *L, lua_Hook func);

, NULL,
. lua_setcallhook
lua_setlinehook
.
call ,
. event ar "call"
"return". ar lua_getinfo,
lua_getlocal lua_setlocal,
.
line ,
, . event ar "line",
currentline . ar
API.
Lua ,
. ,
Lua, chunk,
.
4.7.4

ldblib
Lua. ,
lua_dblibopen.
.
, ,
(, ). ,
.
(,
). ,
, .
getinfo (function, [what])

.
,
function,
function. 0 ( getinfo),
1: , getinfo . function
, , getinfo
nil.
, lua_getinfo
what , . what:
.
, getinfo(1,"n").name ,
, getinfo(print)
print.
getlocal (level, local)

, local
level . 1
. nil,
,
level . getinfo,
, .
setlocal (level, local, value)

value local
level . nil,
,
level .
setcallhook (hook)

hook
call.
.
call: ("call" "return").
getinfo 2,
( 0 getinfo, 1
. ,
call. setcallhook
.
setlinehook (hook)

hook
line. ,
.
line: ,
. ,
line. setlinehook .
4.8 Lua
Lua ,
C, .
Lua, , lua.
:
-sNUM

NUM ( ,
).
stdin .

-c

lua_close .
-e \rmstat
stat.
-f filename

filename arg.
-i
-q

.
.

-v

var=value

var "value".
filename

filename.
, lua lua -v -i, stdin
, lua - .
, -c. , ,
:
$ lua -i a=test prog.lua

EOF stdin, a
"test" prog.lua. $
. .

-f filename,
Lua filename , arg. n
, 0 "filename". ,
$ lua a.lua -f b.lua t1 t3

a.lua, :
arg = {"t1", "t3";

n = 2, [0] = "b.lua"}

b.lua.
getargs, ,
. , Lua :
$ lua -c a b

getargs a b :
{[0] = "lua", [1] = "-c", [2] = "a", [3] = "b", n = 3}

.
(\).
_PROMPT ,
. ,
. :
$ lua _PROMPT='myprompt> ' -i

Lua, _PROMPT.
Unix Lua- ,
chmod +x #! #!/usr/local/bin/lua #!/usr/local/bin/lua -f,
.
4.10
CENPES/PETROBRAS, ,
TeCGraf,
. Carlos Henrique Levy
. Lua .
4.11
Lua 4.0 .
,
Lua, .
.
version 3.2

($debug, $if, ...) .


for, break in .
.
.
, f(g(x)),
g f. , g
f.
,
. ,
.
,
.

next foreach .
.
rawgettable rawsettable
rawget rawset.
foreachvar, nextvar, rawsetglobal rawgetglobal .
,
, globals.
setglobal sort . type
.
p call .

API

API .
.
API .

4.12 Lua
chunk ::= {stat [`;']}
block ::= chunk
stat ::= varlist1 `=' explist1
| functioncall
| do block end
| while exp1 do block end

| repeat block until exp1


| if exp1 then block {elseif
exp1 then block} [else block] end
| return [explist1]
| break
| for `name' `=' exp1 `,'
exp1 [`,' exp1] do block end
| for `name' `,' `name'
in exp1 do block end
| function funcname `(' [parlist1] `)'
block end
| local declist [init] funcname ::= `name'
| `name' `.' `name' | `name'
`:' `name'
varlist1 ::= var {`,' var}
var ::= `name' | varorfunc `[' exp1 `]'
| varorfunc `.' `name'
varorfunc ::= var | functioncall
declist ::= `name' {`,' `name'}
init ::= `=' explist1
explist1 ::= {exp1 `,'} exp
exp1 ::= exp
exp ::= nil | `number' | `literal' | var
| function | upvalue
| functioncall | tableconstructor
| `(' exp `)' | exp binop exp | unop exp
functioncall ::= varorfunc args | varorfunc `:' `name' args
args ::= `(' [explist1] `)' | tableconstructor
| `literal'
function ::= function `(' [parlist1] `)'
block end
parlist1 ::= `...' | `name' {`,'
`name'} [`,' `...']
upvalue ::= `%' `name'
tableconstructor ::= `{' fieldlist `}'
fieldlist ::= lfieldlist | ffieldlist | lfieldlist `;'
ffieldlist | ffieldlist `;' lfieldlist
lfieldlist ::= [lfieldlist1]
ffieldlist ::= [ffieldlist1]
lfieldlist1 ::= exp {`,' exp} [`,']
ffieldlist1 ::= ffield {`,' ffield} [`,']
ffield ::= `[' exp `]' `=' exp
| `name' `=' exp
binop ::= `+' | `-' | `*' | `/'
| `\^{ ' | `..'
| `<' | `<=' | `>'
| `>=' | `==' | `\ { '=}
| and | or}
unop ::= `-' | not

4.13 lua: Lua

lua [arguments]

lua Lua.
Lua, ,
, luac. lua
, .
arguments , .
.
(-) .
a=b, b
a. ,
, ,
. ,
,
.
, , ,
.
, -v -i,
, -.

(-) , ,
.
-c Lua .
-e "stat" stat. stat,
.
-f "file" arg,
file. arg 0,
file. arg.n.

-i , . lua
.
. ,
,
(\).
_PROMPT, . ,
_PROMPT.
"_PROMPT=\'lua: \'".
,
. : >.
-q , .
-sn n. ,
. , n , -s.
, 2000, -s2000.
-v .

luac(1)
http://www.lua.org/.

.
luac: Lua

luac [options] [filenames]

luac Lua. ,
Lua ,
lua_dofile C dofile Lua.
:
,
.
, Lua
- , . luac
- .

luac , -
. luac.out,
-o.
, luac,
. , , 32 ( Intel) 32 ( Sparc), .
, , 16- ,
32- .
,
Lua, , . :
(
) .
"-", stdin .
, luac, ,
Lua.
Lua.

. -l
- Lua.
, luac luac.out .
-o "file" file luac.out.
, ,
.
-p , .
:
, , , .
-t.
-s .
,
,
, .
-t . ,
, ,
. , ,

- . , luac
luac.out .
-v .

luac.out

lua(1)
http://www.lua.org/.

.

R. Ierusalimschy,
L. H. de Figueiredo
W. Celes (
lua@tecgraf.puc-rio.br).

4.14 LUA
Lua Unix :

config, ,
.
make.
Lua "" ,
make install.
config. , ,
root, .

Windows Macintosh.
4.14.1

make , :

./bin/lua, ./bin/luac.
./lib.
./include.

, .
Man- lua luac nroff html, html
./doc, ./test,
./etc. .
README- .
: ./doc/readme.shtml.
4.14.2

make , ,
lua@tecgraf.puc-rio.br. config
Makefile, , .
4.14.3

Linux, make so make.


./lib. ,
, make install.
,
, make sobin.
, , lib
LD_LIBRAY_PATH, ,
,
make install.
,
. Makefile
.
4.14.4 Windows Macintosh

Lua Mac Windows-


, .
, .c .h.
, ,
:
core lib:

lapi.c lcode.c ldebug.c ldo.c lfunc.c lgc.c llex.c lmem.c


lobject.c lparser.c lstate.c lstring.c ltable.c ltests.c
ltm.c lundump.c lvm.c lzio.c
standard lib: lauxlib.c lbaselib.c ldblib.c liolib.c lmathlib.c lstrlib.c
interpreter: core lib, standard lib, lua.c
compiler:
core lib, dump.c luac.c opt.c print.c stubs.c

, Lua , ,

.
4.14.5 INSTALL mysql 3.23.32

LUA 4.0 patched mysql (


).
LUA 4.0, ,
mysql. /usr/src/lua LUA /usr/src/mysql MySQL.
mysql :

cd sql
tar zxf /download/mylua.tar.gz
cd ..
./configure --enable-assembler \
--prefix=/usr/local/mysql \
--enable-assembler \
--with-mysqld-ldflags="-L/usr/src/lua/lib \
-llua -llualib"

mysql mysql
mysql< SELECT user,host FROM user
PROCEDURE("/usr/src/mysql/sql/count.lua")

5. MySQLdb: Python- MySQL


MySQLdb -
MySQL, Python API .
0.9.1 ( Andy Dustman, andy@dustman.net).
GPL
http://sourceforge.net/projects/mysql-python. :

Python API ( 2.0).


- .
.
MySQL-3.23 .

:
Python 1.5.2 :

http://www.python.org
, 1.5.2, .

, 1.5.2, . 1.6.x . 2.0.1,


2.1.1 2.2a3 .
Red Hat Linux ,
Python
(python-devel). Python-2.x python2-devel.

Distutils 1.0.2 :

Python 1.6 .
1.0.2 Python version 2.1 .
http://www.python.org/sigs/distutils-sig/download.html

MySQL 3.22.19 .

http://www.mysql.com/downloads
, 3.22 .
, 3.22.19 .
MySQL-4.0 .
MySQL-3.23 .
Red Hat Linux ,
MySQL.
mysql.com, MySQL-devel.
Red Hat, mysql-devel.
www.mysql.com.

5.1.
, , setup.py.
, MySQL include-
. MySQL Red Hat
Linux (6.2) RPM. ,
.
. distutils ( 1.0.2),
, .
, www.mysql.com
: mysqlclient mysqlclient_r.
- ,
, .
( Linux .so-),
.
,
LD_LIBRARY_PATH ( Linux) ,
. setup.py,

. RPM,
.
: Zope,
setup.py python Zope.
Zope (ZMySQLDA) _mysql.
RPM, bdist_rpm
setup.py. RPM, .
, Joe
Skinner. , :

- (
)
MySQL 3.21 (
)

MySQLdb , GNU
Public License. MySQLdb.
5.1.1
Linux/UNIX

RedHat Linux ( 7.1) Intel.


,
setup.py. MacOS X.
Distutils, Python 2.0.
( Python 1.5.2),
http://www.python.org/.
Windows (3.11, 95, 98, NT, 2000, CE)

Windows . , setup.py
.
5.1.2 Python

MySQLdb Python 1.5.2 .


, MySQL C long long.
Python, 1.5.2.
Python 2.1, Python 1.5.2
.
5.1.3 MySQL

MySQL-3.22

3.22.32 .
, ,
.
MySQL-3.22 TIME
. , 12:56:13.00, 344:13:00,
12 , 56 , 13 0 (12
56 =344 ). ,
DateTimeDelta.
MySQL-3.23

MySQLdb , .
, .
- (TST). TST: BDB InnoDB.
GEMINI MySQL-4.0. , MySQL
AUTOCOMMIT , MySQLdb ,
AUTOCOMMIT . , SQL SET
AUTOCOMMIT=0.
5.1.4 DateTime

mx.DateTime , MySQLdb
. .
,
.
5.1.5 MySQLmodule

MySQLmodule, MySQL, Joe Skinner,


C/Python. MySQL, C-, , perl DBI.
, Python, Mysqldb, DB
API v1.0, James Henstridge. MySQLdb-0.2.2
CompatMysqldb, Mysqldb _mysql.
.
, C- MySQLdb, _mysql, MySQL C API
- . MySQLdb DB API
v2.0, v1.0, :

Mysqldb

MySQLdb

db=Mysqldb.Mysqldb("db@host
user pass")

db=MySQLdb.connect(db='db',
host='host', user='user',
passwd='pass')

db.execute(SQL)

DB API
v2.0.
c=db.cursor()

:
DictCursor

, "column"
c.fetchDict(), :

"table.column ,
"table.column"

.
SQL- AS
.
db.commit() db.rollback()
db.commit() db.rollback()
, MySQL

,
(!) db.rollback()
.
5.1.6 Zope ZMySQLDA

ZMySQLDA MySQLdb.
ZOracleDA Digital Creations Zope.
5.1.7 FAQ

FAQ http://dustman.net/andy/python/MySQLdb/faq/MySQLdb-FAQ.html.
5.2. _mysql
,
, .
_mysql , MySQL C API.

MySQL. , ,
, ( MySQLdb).
5.2.1 MySQL C API

MySQL C API - .
MySQL , , MYSQL
( ) MYSQL_RES ( ).
, , MYSQL *mysql,
, ,
MYSQL_RES *result, . ,
MySQL, . ,
- MySQL, .
mysql_ .

MySQLdb Connection.
.
conn

C API

_mysql

mysql_affected_rows()

conn.affected_rows()

mysql_close()

conn.close()

mysql_connect()

_mysql.connect()

mysql_data_seek()

result.data_seek()

mysql_debug()

_mysql.debug()

mysql_dump_debug_info

conn.dump_debug_info()

mysql_escape_string()

_mysql.escape_string()

mysql_fetch_row()

result.fetch_row()

mysql_get_client_info()

_mysql.get_client_info()

mysql_get_host_info()

conn.get_host_info()

mysql_get_proto_info()

conn.get_proto_info()

mysql_get_server_info()

conn.get_server_info()

mysql_info()

conn.info()

mysql_insert_id()

conn.insert_id()

mysql_list_dbs()

conn.list_dbs()

mysql_list_fields()

conn.list_fields()

mysql_list_processes()

conn.list_processes()

mysql_list_tables()

conn.list_tables()

mysql_num_fields()

result.num_fields()

mysql_num_rows()

result.num_rows()

mysql_options()

_mysql.connect()

mysql_ping()

conn.ping()

mysql_query()

conn.query()

mysql_real_connect()

_mysql.connect()

mysql_real_query()

conn.query()

mysql_real_escape_string() conn.escape_string()
mysql_row_seek()

result.row_seek()

mysql_row_tell()

result.row_tell()

mysql_select_db()

conn.select_db()

mysql_stat()

conn.stat()

mysql_store_result()

conn.store_result()

mysql_thread_id()

conn.thread_id()

mysql_use_result()

conn.use_result()

CLIENT_*

MySQLdb.constants.CLIENT.*

CR_*

MySQLdb.constants.CR.*

ER_*

MySQLdb.constants.ER.*

FIELD_TYPE_*

MySQLdb.constants.FIELD_TYPE.*

FLAG_*

MySQLdb.constants.FLAG.*

5.2.2 _mysql

, _mysql. .
:
import _mysql
db=_mysql.connect()

MySQL ,
UNIX, (
USER), USE. ,
, (~/.my.cnf ).
:
db=_mysql.connect("localhost","joebob","moonpie","thangs")

MySQL , TCP
(3306), joebob, moonpie
thangs.
, TCP, .
connect(), , ,
, TCP -
. , UNIX .
:
db=_mysql.connect(host="localhost",user="joebob",
passwd="moonpie",db="thangs")

, , . ,
UNIX,
joebob, :
db=_mysql.connect(passwd="moonpie",db="thangs")

, ,
, , .
. Python 2.1 pydoc
.
db .
MySQL ,
db.query():

db.query("""SELECT spam, eggs, sausage FROM breakfast


WHERE price < 5""")

,
. ,
_mysql_exceptions, _mysql . DB API
(http://www.python.org/topics/database/DatabaseAPI-2.0.html), ,
, MySQLError.
, .
:
r=db.store_result()
# ......
r=db.use_result()

. ? ,
store_result() .
, .
, LIMIT
, .
use_result(),
, . :
, .
store_result(),
, LIMIT.
:
>>> r.fetch_row()
(('3','2','0'),)

, : fetch_row()
. , (maxrows)
. , .
, , .
maxrows=0, .
- , .
(how) . ,
, . how=1
, table.column,
. how=2 how=1, ,
table.column,
Mysqldb.
: , ,
? , MySQL

, .
, ,
. , _mysql
. MySQLdb .
,
connect() conv.
conv MySQL, C API
FIELD_TYPE_*. :
from MySQLdb.constants import FIELD_TYPE

, conv,
, .
:
my_conv = {FIELD_TYPE.LONG: int}

, FIELD_TYPE_LONG, int().
, FIELD_TYPE_LONG INTEGER,
C long, ,
Python. : UNSIGNED
INTEGER, . MySQLdb
long(), .
, db=_mysql.connect(conv=my_conv...),
((3, 2, 0),), , .
5.3. MySQLdb: DB API
MySQLdb Python _mysql. MySQLdb
Python DB API (version 2).
, API, _mysql
.
5.3.1


MySQLdb.
connect(parameters...)
.
(Connection Object). , MySQL C API. ,
,
, mysql_options()

. ,
!
: NULL 0, . :
host
, :
.
user
, . :
.
passwd
, . :
( ).
db
, . :
.
port
TCP- MySQL. :
(3306).
unix_socket
UNIX. : TCP.
conv
. :
MySQLdb.converters.conversions.
compress
. : .
connect_timeout
,
. : -.
named_pipe
( Windows).
: .
init_command
, .
: .
read_default_file
MySQL. mysql_options().
read_default_group
.
mysql_options().
cursorclass
, cursor(), .
: MySQLdb.cursors.Cursor.
.
apilevel
, DB API: '2.0'.
threadsafety

Integer, ,
. MySQLdb version 0.9.0
1, : .
MySQL ,
, . MySQLdb
, threadsafety=2. ,
Cursor (
mysql_store_result()), SSCursor (
mysql_use_result(). ,
, .
,
, COMMIT ROLLBACK
Connection.
, ,
.
, .
:
. , ,
, MySQL
. , ,
,
.
, MySQL, ,
.
paramstyle
, ,
. 'format'=ANSI C
printf- , '...WHERE name=%s'.
conn.execute(),
'pyformat'= Python, ,
'...WHERE name=%(name)s'. , API
, paramstyle.
: MySQLmodule
, ,
, ,
. MySQLdb.
, %s ( '%s') ,
.
.
conv

, MySQL ( FIELD_TYPE.*)
Python ( ),
.
. Connection

.
MySQLdb.converters.conversions.
DateTime, .
,
MySQL-3.23, MySQL
,
mysql_real_escape_string(). ,
, connection. MySQLdb
. ,
- ,
.
5.3.2 Connection

Connection connect().
commit()
,
, .
rollback()
,
,
NotSupportedError.
: MySQLmodule
, . ,
, .
cursor([cursorclass])
MySQL , , .

. ,
Cursor.
begin()
. :
,
. AUTOCOMMIT,
begin() . AUTOCOMMIT
commit() rollback.

5.3.3 Cursor

callproc()
.
close()
.
ProgrammingError. ,
, ,
.
insert_id()
AUTO_INCREMENT,
.
info()
.
.
MySQL Warning.
,
info(). MySQL mysql_info().
setinputsizes()
.
setoutputsizes()
.
5.3.4

connect() , _mysql:
import MySQLdb
db=MySQLdb.connect(passwd="moonpie",db="thangs")

, ,
.
c=db.cursor()
max_price=5
c.execute("""SELECT spam, eggs, sausage FROM breakfast
WHERE price < %s""", (max_price,))

max_price=5. %s?
, MySQLdb SQL,
'5'. , :
"...WHERE price < 5".
, :
>>> c.fetchone()
(3L, 2L, 0L)

_mysql, ,
, .
, MySQL INTEGER
Python integer, UNSIGNED INTEGER ,
Python long integer. Python 1.6 long integer
L, str(). 1.6 str()
L. , L repr().
, db.commit()
db.rollback(). , commit()
, rollback() .
, connection, cursor, ,
c.execute(...).
,
c.fetchmany(n) c.fetchall(). c.fetchmany(n) n
c.arraysize ( 100).
,
, .
, , c.fetchone()
None, .
, , , ,
:
c.execute("""INSERT INTO breakfast (name, spam, eggs, sausage, price)
VALUES (%s, %s, %s, %s, %s)""",
[ ("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ),
("Not So Much Spam Plate", 3, 2, 0, 3.95 ),
("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 )])

. ,
(, int, float), %s.
, .
MySQLdb .
5.4.
, SQL- ,
. DB API
, .
connect() .

,
, ,
: API
,
, .
API ,
, ,
. ,

.
SQLDict
(http://dustman.net/andy/python),
, , ,
.
MySQLdb Connection Cursor Python,
. Cursor
MySQLdb.cursors:
BaseCursor
Cursor. Warning.
CursorWarningMixIn
Warning ,
.
CursorStoreResultMixIn
Cursor mysql_store_result(),
.
.
CursorUseResultMixIn
mysql_use_result(),
.
.
CursorTupleRowsMixIn
cursor .
CursorDictRowsMixIn
cursor ,
, . ,
, , ,
, ,
table.column. ,
SQL AS
Cursor
.
CursorWarningMixIn, CursorStoreResultMixIn, CursorTupleRowsMixIn

BaseCursor, Warning,
mysql_store_result() .

DictCursor
Cursor ,
.
SSCursor
. Cursor, CursorUseResultMixIn.
,
.
SSDictCursor
SSCursor ,
.
XXXCursorNW
NW Warning.
5.5. MySQLdb FAQ
5.5.1. _mysql.so

, .
UNIX/Linux,
Windows. .so
Linux UNIX. Windows
.dll.
5.5.1.1 ImportError: libmysqlclient.so.6: cannot open shared object
file: No such file or directory

MySQL,
_mysql.so , ,
Python. :
1. setup.py ,
: - .
2.
, setup.py.
3. , MySQL
. Linux /etc/ld.so.conf
LD_LIBRARY_PATH
Python.
4. LD_LIBRARY_PATH=/path/to/mysql/libs python ... # Bourne-ish shell

5.5.1.2 ImportError: ./_mysql.so: undefined symbol:


PyLong_FromUnsignedLongLong

Python 1.5.2,
. ,
. Python 1.5.2 ( ) python.org.
PyLong_FromUnsignedLongLong()

5.5.1.3 ImportError: ./_mysql.so: undefined symbol: uncompress

MySQL-3.23 libz gzip.


setup.py .
5.5.1.4 ./_mysql.c:33: mysql.h: No such file or directory

include- (-I) MySQL include- .


setup.py. : MySQL.
Red Hat RPM, RPM- MySQL-devel,
_mysql.so. ,
MySQL, _mysql.so
, MySQL (libmysqlclient).
5.5.1.5 Windows...

Windows. setup.py, , .
- .
5.5.2. ZMySQLDA
5.5.2.1 MySQLdb, ZMySQLDA

, Zope,
Python. MySQLdb
Python. ,
python , setup.py.
5.5.2.2 L INTEGER

- ,
UNSIGNED INT. :
fmt=%d dtml-var Zope 2.4,
Python 2.1, L.
5.5.2.3 SQL
LIMIT, LIMIT!

Z SQL max_rows. ,
, ZMySQLDA LIMIT
SELECT. , ,
. -,
max_rows , LIMIT. , ,

,
AUTO_INCREMENT, SELECT,
LAST_INSERT_ID(), LIMIT .
5.5.3. MySQLdb

MySQLdb , Python
Database API 2.0 (http://www.python.org/topics/database/DatabaseAPI-2.0.html),
. :
http://dustman.net/andy/python/MySQLdb/doc/MySQLdb.html.
5.5.3.1 cursor.rollback() !

MySQLdb ,
- (TST), .
, rollback ,
.
- , rollback ,
-TST .
cursor.commit(),


, MySQL auto-commit mode
( ).
5.5.3.2
MySQL?

, . , .
.
,
API _mysql, MySQLdb
.
5.5.3.3 _mysql

, - . ZMySQLDA
, Zope- ZRDB API, API
. - .
, ,
.
1. MySQL, C API .
2. MySQLdb. , C API
Python. , .

3. MySQLdb,
MySQLdb/cursors.py. ,
_query.
5.6. MySQLmodule-1.4
Linux (RH50), MySQL 3.21.30 Python 1.5.1.
MySQLmodule-1.x mySQLmodule-0.1.4, :

Copyright (C) 1997 Joseph Skinner JOE@EARTHLINK.CO.NZ


Copyright (C) 1997 James Henstridge JAMES@DAA.COM.AU

mySQLmodule-0.1.4 mSQLmodule, :

Portions copyright (C) 1995 Thawte Consulting, cc


Portions copyright (C) 1994 Anthony Baxter

5.6.1 Python/MySQL?

, ASCII- (\0)
MySQL. Python (
), mySQLmodule
. ,
MySQL API ,
, mySQLmodule
. .
Python ,
MySQL,
(mySQL).
.
, DB
,
.
Data = DBH['select * from MyTable']
if Data:
rows = len(Data)
cols = len(Data[0])
for i in range(rows):
for j in range(cols):
if not Data[i][j]: Data[i][j] = DefaultElement()
Do_Something(Data)


. , , STH fetchdict()

.
(, ) .
5.6.2 MySQL

MySQLmodule.c Modules
Python.
Setup :

MySQL MySQLmodule.c -L/usr/local/lib/mysql/ -lmysqlclient \


-I/usr/local/include/mysql

, MySQL include .
( shared
Setup).

Python , make
Python. , ,
Python.


python, :
gcc -shared -I/usr/include/python1.5 -I/usr/local/include/mysql \
MySQLmodule.c -lmysqlclient -L/usr/lib/python1.5/config \
-lpython1.5 -o MySQLmodule.so

MySQLmodule.so PYTHONPATH.
include-.
, ,
MySQL, ,
mySQL.
,

MySQL :

DBH_Type:
.
STH_Type:
( ,
TypeError).
__doc__:
, Python

connect([host[,user[,pass]]])
.
: (host), ,
username MySQL password.
, localhost (
Unix- ).
escape(string)
, DB.
mysql_escape_string(), 3.21.29gamma . 3.21.30 .
: "" " "
( fetchdict). MySQL.connect()
(DBH) :

Table = DBH.listdbs([wild])
, MySQL,
MySQL.connect().
: MySQL- (
LIKE).
DBH.selectdb(DB_Name[,storage])
.
,
selectdb. storage integer
,
. ,
,
. : 0,
.
Table = DBH.listtables([wild])
.
, selectdb.
,
( ,
LIKE).
Table = DBH.listfields(table[,wild])
.
,
( , LIKE).
Table = DBH.listprocesses()
MySQL.
( None).
String = DBH.stat()
MySQL.
DBH.create(DB_Definition)
.

DBH.drop(DB_Name)
.
DBH.reload()
MySQL.
DBH.shutdown()
MySQL.
DBH.close()
DB-.
String = DBH.clientinfo()
MySQLmodule.
String = DBH.serverinfo()
MySQL.
String = DBH.hostinfo()

.
Integer = DBH.protoinfo()
MySQL.
Table = DBH.do(query) Table = DBH[query]
SQL .
, DBH.selectdb().
Integer = DBH.insert_id()

auto_increment. ,
.
STH = DBH.query(query[,storage])
(. ).
storage ,
DBH, DBH.selectdb().

(STH):

Table = STH.fetchrows([n])
DB. n<0, .
n .
.
Table = STH.fetchdict([n])
STH.fetchrows(), ,
tablename.fieldname:data.
Table = STH.fields()
STH.
MySQLmodule "pri", "notnull", "auto_inc", "ukey" "mkey" .
STH.seek(n)
n (0 ). ,
( DBH.selectdb).
.

Integer = STH.numrows()
, STH.
:
. ,
0 , .

.
Integer = STH.numfields()
, STH.
Integer = STH.affectedrows()
.
, MySQL
.
Integer = STH.insert_id()
auto_increment STH- insert.
, , STH .
Integer = STH.eof()
1, , 0. 1,
(
).

MySQL
import MySQL
DBH = MySQL.connect()
# localhost
print DBH.listdbs()
DBH.selectdb('test')
print DBH.serverinfo()
print DBH.stat()
DBH["create table pytest (x int, y int, s char(20))"]
DBH["insert into pytest values (1,2,'abc')"]
DBH.do("insert into pytest values (3,4,'def')")
STH = DBH.query("insert into pytest values (5,6,'ghi')")
print STH.affectedrows()
print DBH['select * from pytest']
STH = DBH.query("select * from pytest")
print STH.numrows()
print STH.fields()
print STH.fetchrows(-1)
STH.seek(0)
print STH.fetchrows(1)
print STH.fetchrows(1)
STH.seek(0)
print STH.fetchrows(2)
print STH.fetchrows(2)
print STH.numfields()
STH.seek(0)
print STH.fetchdict(1)
print STH.fetchdict()
STH = DBH.query("select * from pytest",1)
print STH.fetchdict(1)
print STH.fetchdict() # compare to previous dicts
STH = DBH.query("select * from pytest",1)
print STH.fetchrows(1)

print STH.eof()
print STH.fetchrows()
print STH.eof()
DBH['drop table pytest']

5.6.3

MySQL .
MySQLmodule ,
, ,
(STH), .
STH.fetchrows(n) STH.fetchdict(n) (n=1), (n>1),
(n<0) (n=0).
STH.numrows()
. STH.seek(k) ,
.
, , .
:
STH = DBH.query("select * from Foo")
N = STH.numrows()
if N > 1000: raise Hell,"You must be joking!"
for i in xrange(N):
[Data] = STH.fetchdict(1)

,
, ,
. , STH.eof() true (1)
.
, .
. ,
. ,
, ,
, . ,
, ,
, . MySQL API 3.21
abort(). STH.numrows() ,
,
. STH.numrows() , , , , :
STH = DBH.query("select * from Foo")
Data = STH.fetchrows(-1)
print "Got",STH.numrows(),"rows."
# len(Data) is the same

STH.eof() ,
:
STH = DBH.query("select 1")
print STH.eof()
# will print 0
Data = STH.fetchrows(1) # retrieve the row
print STH.eof()
# still 0 :-(
Data = STH.fetchrows(1) # must repeat. Data will be []
print STH.eof()
# now we get 1, but we already
# knew that we've hit the end

, . STH.seek(k)
("cannot seek on server"),
.
.
, ,
.
, ,
(, Ctrl-S ).
, ,
, MySQLmodule .
DBH.selectdb()
(STH). ,
:
STH = DBH.query("select * from Foo",1) # use server side storage
Tables = DBH.listtables()
# stomp on previous results
Data = STH.fetchrows()
# nothing here anymore vs.
STH = DBH.query("select * from Foo",0) # use client side storage
Tables = DBH.listtables()
# won't interfere
Data = STH.fetchrows()
# no problem...

MySQLmodule.
STH-
.
, ,
DBH. .

STH. MySQLmodule , ,
. , mysql_close()
, , DBH, :
DBH = MySQL.connect()
# get a DB handle
STH = DBH.query("select 1",1) # server side cursor
del DBH
# mysql_close() *not* called
STH.fetchrows()
# will succeed!

del STH

# now mysql_close() will be called


# in DBH_dealloc()

DB , DBH.close().
(
) "...
server has gone away". , mySQL
, DBH-
STH-. , DBH
STH-.
5.6.4 MySQLmodule-1.4 Windows NT

, Nigel Head
(nhead@houbits.com).

libMySQL.dll win32mysql 3.22.8 , .


www.tcx.se ( ) . ,
, ,
python15.dll.
MySQLmodule-1.4 WIN32.
VC5 MySQL.dsp MySQL.dsw (, ,
, ).
MySQL.pyd
Python DLL.

- ,
comp.lang.python.
5.7 Python Database API 2.0
API , Python,
, .
Python Database API 2.0.
:






1.0 2.0


db-sig@python.org.


Python
http://www.python.org/topics/database.
5.7.1

.
:
connect(parameters...)
.
. ,
.
:
apilevel
, DB API.
'1.0' '2.0'. ,
Database API 1.0.
threadsafety
, ,
. :
0 .
1 , .
2 .
3 , .
,
, mutex, . ,
-
, mutex:
,
!
paramstyle
. ,
. :
'qmark'
, , '...WHERE name=?'
'numeric' , , , '...WHERE name=:1'
'named'
, , '...WHERE name=:name'
'format'
ANSI C printf, , '...WHERE name=%s'
Python, ,
'pyformat'
'...WHERE name=%(name)s'


:
Warning

. . Python
StandardError.
Error
,
. ,
'except'.

. Python
StandardError.
InterfaceError
,
, . Error.
DatabaseError
,
. Error.
DataError
, -
, ,
.. DatabaseError.
OperationalError
,
, ,
, ,
,
..
DatabaseError.
IntegrityError
,
, ,
. DatabaseError.
InternalError
,
, , ,
, - .
DatabaseError.
ProgrammingError
, ,
,
SQL, ..
DatabaseError.
NotSupportedError

,
API , , ,
rollback() ,
.
DatabaseError.
,
, ,
.
, Python
AttributeError , .
,
hasattr().
:
StandardError
|__Warning
|__Error
|__InterfaceError
|__DatabaseError
|__DataError
|__OperationalError
|__IntegrityError
|__InternalError
|__ProgrammingError
|__NotSupportedError

: .
, .
5.7.2

:
close()
. ,
. - ,
Error ( ).
,
.
commit()
.
, auto-commit,
. ,
.

, ,

.
rollback()
,
.
,
.
, ,
.
cursor()
, .
() ,
,
.


:

user

password
host

database

dsn

, :
connect(dsn='myhost:MYDB',user='guido',password='234+$').
5.7.3

, ,
.
:
description
:
7 . ,
: (name, type_code,
display_size, internal_size, precision, scale, null_ok).
None , ,
, executeXXX().

type_code , Type Objects,


.
rowcount
,
executeXXX() ( SQL-, select)
( SQL-, update insert).
-1 , executeXXX()
.
callproc(procname[,parameters])
:
. .

, .
.
, -
.
.
fetchXXX().
close()
,
. - ,
Error ( ).
execute(operation[,parameters])
( ).
.
.
.
.
,
. ,
, .

, setinputsizes(),
.
:
, , .
, , ,
,
: executemany().
executemany(operation,seq_of_parameters)

( ),
,
seq_of_parameters.
,
execute() ,
.
, execute(),
. .
fetchone()
,
None,
. Error ( ) ,
executeXXX()
.
fetchmany([size=cursor.arraysize])
,
(, tuples).
, .
, , .
, arraysize ,
. ,
. - ,
.
Error ( ) ,
executeXXX()
.
, ,
.
, arraysize.
fetchall()
,
(, tuples).
, arraysize
. Error (
) , executeXXX()
.
nextset()
,
.

,
() .
, None.
true,
.
Error ( ) ,
executeXXX()
.
, ,
. ,
.
arraysize
- ,
fetchmany() . 1 (
)

fetchmany(),
- .
executemany().
setinputsizes(sizes)
executeXXX()
. sizes
:
. Type Object, ,
, ,
.
None,
( ,
).
.
setoutputsize(size[,column])

(, LONG, BLOB ).
. column
.
.
5.7.4


. ,
DATE,
. "Row ID"
(, blob RAW).
Python,
executeXXX(). ,
, .
, ,
, ,
. ,
.
description
. type_code
Type Objects, . Type Objects
, (, DATETIME
, ).
:
Date(year,month,day)
, .
Time(hour,minute,second)
, .
Timestamp(year,month,day,hour,minute,second)
, .
DateFromTicks(ticks)
,
( , epoch,
Python time).
TimeFromTicks(ticks)
,
( , epoch,
Python time).
TimestampFromTicks(ticks)
,
( , epoch,
Python time).
Binary(string)
,
long.
STRING
, ,
(, CHAR).

BINARY
, (long)
(, LONG, RAW, BLOB).
NUMBER
, .
DATETIME
, /
.
ROWID
, "Row ID" .
SQL- NULL Python None.
: Unix-
-
, .
5.7.5

/
mxDateTime (
http://starship.python.net/~lemburg/mxDateTime.html).
Python C.
Binary
, Python, 1.5.2.
Python
( Include/bufferobject.h Objects/bufferobject.c).
/,
Unix :

import time

Python
, type
object:

class DBAPITypeObject:
def __init__(self,*values):

def DateFromTicks(ticks):
return apply(Date,time.localtime(ticks)[:3])
def TimeFromTicks(ticks):
return apply(Time,time.localtime(ticks)[3:6])
def TimestampFromTicks(ticks):
return apply(Timestamp,time.localtime(ticks)[:6])

self.values = values
def __cmp__(self,other):
if other in self.values:
return 0
if other < self.values:
return 1
else:
return -1

,
.

Python,
, :

import exceptions
class Error(exceptions.StandardError):
pass
class Warning(exceptions.StandardError):
pass
class InterfaceError(Error):
pass
class DatabaseError(Error):
pass
class InternalError(DatabaseError):
pass
class OperationalError(DatabaseError):
pass
class ProgrammingError(DatabaseError):
pass
class IntegrityError(DatabaseError):
pass
class DataError(DatabaseError):
pass
class NotSupportedError(DatabaseError):
pass

C API
PyErr_NewException(fullname,base,NULL),

.
5.7.6 1.0 2.0

Python Database API 2.0


1.0.
DB API.

dbi ,
,
.
Type Objects
/, RAW Type Object BINARY.
,
SQL.
(apilevel, threadlevel, paramstyle)
(executemany, nextset),
.
callproc(), ,
.
execute() .
SQL ( -
), ,
rowcount .
,
.

. ,
,
.

2.0 ,
1.0, :

nextset() ,
.

.

,
-.
, fetchXXX().
__getitem__ ,
( ) () .
, .
.
,
. , ,
:
.
rowcount ,
. ,
rowcount
fetchXXX().

6 MySQL DELPHI API


. ,
(16 ),
( 16 ).
,
, .
.
,
SQL ( "- ")
( "--").
,
. , BLOB,
16M , 16M
( ).
16M, 1M.
, max_allowed_packet
.
MySQL net_buffer_length
. , ,
, .
6.1 DELPHI API
TMYSQL

.
MySQL.
TMYSQL_RES

,
(SELECT, SHOW, DESCRIBE, EXPLAIN). , ,
.

TMYSQL_ROW

- .
.
,
,
. ,
mysql_fetch_row().
TMYSQL_FIELD

, ,
, . .
TMYSQL_FIELD ,
mysql_fetch_field(). ,
TMYSQL_ROW.

TMYSQL_FIELD_OFFSET

- MySQL.
mysql_field_seek().
, .
Tmy_ulonglong

, mysql_affected_rows(),
mysql_num_rows() mysql_insert_id().
0 1.84e19.
Tmy_ulonglong . ,
longint.
TMYSQL_FIELD , :
name:pchar;

, .
table:pchar;

, , .
, table .

def:pchar;

,
. , mysql_list_fields().
typ:TFIELD_TYPES;

. typ :
Typ

FIELD_TYPE_TINY
FIELD_TYPE_SHORT
FIELD_TYPE_LONG
FIELD_TYPE_INT24
FIELD_TYPE_LONGLONG

TINYINT
SMALLINT
INTEGER
MEDIUMINT
BIGINT

FIELD_TYPE_DECIMAL
FIELD_TYPE_FLOAT
FIELD_TYPE_DOUBLE
FIELD_TYPE_TIMESTAMP
FIELD_TYPE_DATE
FIELD_TYPE_TIME
FIELD_TYPE_DATETIME
FIELD_TYPE_YEAR
FIELD_TYPE_STRING
FIELD_TYPE_BLOB
FIELD_TYPE_SET
FIELD_TYPE_ENUM
FIELD_TYPE_NULL
FIELD_TYPE_CHAR
length:longword;

DECIMAL
FLOAT

NUMERIC

DOUBLE REAL
TIMESTAMP
DATE
TIME
DATETIME
YEAR

(CHAR VARCHAR)
BLOB TEXT ( max_length,
)
SET
ENUM
NULL

: FIELD_TYPE_TINY

, .
max_length:longword;

(
).
mysql_store_result() mysql_list_fields(),
. mysql_use_result(),
.

flags:longword;

. flags
:
Flags

NOT_NULL_FLAG
NULL
PRI_KEY_FLAG

UNIQUE_KEY_FLAG

MULTIPLE_KEY_FLAG

UNSIGNED_FLAG
UNSIGNED
ZEROFILL_FLAG
ZEROFILL
BINARY_FLAG
BINARY
AUTO_INCREMENT_FLAG AUTO_INCREMENT
ENUM_FLAG
ENUM
BLOB_FLAG
BLOB TEXT
TIMESTAMP_FLAG
TIMESTAMP
BLOB_FLAG, ENUM_FLAG TIMESTAMP_FLAG
, , .
field.typ FIELD_TYPE_BLOB, FIELD_TYPE_ENUM
FIELD_TYPE_TIMESTAMP.
flags:
if (field.flags & NOT_NULL_FLAG) write("Field can't be null");

,
flags:
IS_NOT_NULL(flags) , NOT NULL
IS_PRI_KEY(flags)
IS_BLOB(flags)

,
, BLOB TEXT

decimals:longword;

.
6.2 Delphi API

, Delphi API,
. " Delphi API".

UPDATE, DELETE INSERT.
mysql_close()
.
mysql_connect()
.

mysql_change_user()
.
. SQL CREATE
mysql_create_db()
DATABASE.

mysql_data_seek()
.
DBUG_PUSH .
mysql_debug()
.
mysql_drop_db()
SQL DROP DATABASE.

mysql_dump_debug_info()
.
,
mysql_eof()
.

mysql_errno()
MySQL.

mysql_error()
MySQL.

SQL,
mysql_real_escape_string()

.

mysql_escape_string()
SQL.
mysql_fetch_field()
.
mysql_fetch_field_direct() , .
mysql_fetch_fields()
.
mysql_affected_rows()

mysql_fetch_lengths()
mysql_fetch_row()
mysql_field_seek()
mysql_field_count()
mysql_field_tell()
mysql_free_result()
mysql_get_client_info()
mysql_get_host_info()
mysql_get_proto_info()
mysql_get_server_info()
mysql_info()
mysql_init()
mysql_insert_id()
mysql_kill()
mysql_list_dbs()
mysql_list_fields()
mysql_list_processes()
mysql_list_tables()
mysql_num_fields()
mysql_num_rows()
mysql_options()
mysql_ping()
mysql_query()
mysql_real_connect()
mysql_real_query()
mysql_reload()
mysql_row_seek()


() .
.

.

.
,
mysql_fetch_field().
,
.
-.
, .
,
.
.

.
MYSQL.
ID,
AUTO_INCREMENT .
.
,
.
,
.
.
,
.
.
.

mysql_connect().
,
.
SQL,
.
.
SQL,
.
,
.
,

mysql_row_tell()
mysql_select_db()
mysql_shutdown()
mysql_stat()
mysql_store_result()
mysql_thread_id()
mysql_thread_safe()
mysql_use_result()

, mysql_row_tell().
.
.
.
.
.
ID .
1, .
.

, mysql_init(),
, mysql_real_connect()
( hostname, ).
mysql_real_connect() reconnect (
MYSQL) 1. ,
- ,
.
, mysql_close() .
, SQL
, mysql_query() mysql_real_query().
, mysql_query() ,
, mysql_real_query()
. (
),
mysql_real_query().
-SELECT (, INSERT, UPDATE, DELETE),
, , mysql_affected_rows().
SELECT .
, SELECT ,
. SHOW, DESCRIBE EXPLAIN.
, SELECT.
, .
, ,
mysql_store_result(). ,
.
, mysql_use_result().
, .
, mysql_fetch_row().
mysql_store_result() mysql_fetch_row() ,

. mysql_use_result() mysql_fetch_row()
.
mysql_fetch_lengths().
, ,
mysql_free_result(), .
.
, .
,
mysql_store_result().
mysql_store_result() , ,
,
, ,
mysql_data_seek() mysql_row_seek(),
() .
, , mysql_num_rows(). ,
mysql_store_result()
, , ,
.
mysql_use_result() ,
,
( ,
, mysql_use_result()
). : ,
.
(
), , ,
. , ,
, ,
.
API (
) , ,
SELECT. , mysql_store_result()
mysql_query() ( mysql_real_query()).
, SELECT, .
, mysql_field_count(), ,
. mysql_field_count() ,
( , INSERT, UPDATE,
DELETE - ) . mysql_field_count()
, , .
, SELECT, .

mysql_store_result() mysql_use_result()
, (
, , ..).
, mysql_fetch_field() ,
, mysql_fetch_field_direct() .
()
mysql_field_seek().
mysql_fetch_field().
, mysql_fetch_fields().
MySQL
mysql_errno() mysql_error().

, , , .
6.3 API
NULL NULL
C, MySQL- NULL.
, , .
, , ,
-NULL, , NULL, ,
, , ,
, , . ,
" " .
, - ,
.
if (result)
... error ...
if (result < 0)
... error ...
if (result = -1)
... error ...

/* */
/* */
/* */

,
. ,
, mysql_errno().
, mysql_error().
6.3.1 mysql_affected_rows()
tmy_ulonglong mysql_affected_rows(mysql:PMYSQL):TMY_ULONGLONG; stdcall;

, UPDATE,
DELETE INSERT.
mysql_query() UPDATE, DELETE INSERT.
SELECT mysql_affected_rows() mysql_num_rows().

, , , .
, . -1 ,
, SELECT mysql_affected_rows()
mysql_store_result().
CLIENT_FOUND_ROWS, mysqld
mysql_affected_rows() , WHERE
UPDATE.
, , REPLACE,
mysql_affected_rows() 2 ,
, .
6.3.2 mysql_close()
mysql_close(sock:PMYSQL);stdcall;

. mysql_close()
, mysql,
mysql_init() mysql_connect().

.
6.3.3 mysql_connect()
mysql_connect(mysql: PMYSQL; const host,user,passwd:pchar):PMYSQL;
stdcall;

MySQL host.
mysql_connect() ,
API, mysql_get_client_info().

,
mysql_real_connect() ,
NULL. API
, mysql_close().
, ,
.
mysql_errno() mysql_error(),
MYSQL.

mysql_real_connect().

mysql_real_connect().
6.3.4 mysql_change_user()
mysql_change_user(mysql: PMYSQL; const user,passwd,
db:pchar):TMY_BOOL;stdcall;

, db,
() ,
mysql.
, .
MySQL Version 3.23.3.
,
, .
.
mysql_change_user()

db NULL,
.

. , .

mysql_real_connect().
CR_COMMANDS_OUT_OF_SYNC

.
CR_SERVER_GONE_ERROR

MySQL .

CR_SERVER_LOST

.
CR_UNKNOWN_ERROR

ER_UNKNOWN_COM_ERROR

MySQL (, ).
ER_ACCESS_DENIED_ERROR

ER_BAD_DB_ERROR

.
ER_DBACCESS_DENIED_ERROR

ER_WRONG_DB_NAME

.
6.3.5 mysql_create_db()
mysql_create_db(mysql:PMYSQL; const db:pchar):integer;stdcall;

db.

, . ,
.

CR_COMMANDS_OUT_OF_SYNC

.
CR_SERVER_GONE_ERROR

MySQL .

CR_SERVER_LOST

.
CR_UNKNOWN_ERROR

.
6.3.6 mysql_data_seek()
mysql_data_seek(res:PMYSQL_RES;offset:TMY_ULONGLONG); stdcall;

. ,
,
mysql_data_seek()
mysql_store_result(), mysql_use_result().
0 mysql_num_rows(result)1.
6.3.7 mysql_debug()
mysql_debug(const debug:pchar);stdcall;

DBUG_PUSH . mysql_debug()
Fred Fish. ,
, .

, ,
/tmp/client.trace :
mysql_debug("d:t:O,/tmp/client.trace");

6.3.8 mysql_drop_db()
mysql_drop_db(mysql:PMYSQL; const db:pchar):integer;stdcall;

, db.

, . ,
.

CR_COMMANDS_OUT_OF_SYNC

CR_SERVER_GONE_ERROR

MySQL .
CR_SERVER_LOST

CR_UNKNOWN_ERROR

.
6.3.9 mysql_dump_debug_info()
mysql_dump_debug_info(mysql:PMYSQL):integer;stdcall;

,
. process,
.

, . ,
.

CR_COMMANDS_OUT_OF_SYNC

.
CR_SERVER_GONE_ERROR

MySQL .

CR_SERVER_LOST

.
CR_UNKNOWN_ERROR

.
6.3.10 mysql_eof()
mysql_eof(res:PMYSQL_RES):TMY_BOOL;stdcall;

mysql_eof()

, .


mysql_store_result(), .
NULL mysql_fetch_row() ,
mysql_eof().
, mysql_use_result(),
,
, mysql_fetch_row() .
,
NULL mysql_fetch_row() ,
. , mysql_eof(),

, . mysql_eof() ,
, ,
.
mysql_eof() MySQL
mysql_errno() mysql_error().
, mysql_eof().
, ,
mysql_eof() ,
.

mysql_eof() , ,
, .
6.3.11 mysql_errno()
mysql_errno(mysql:PMYSQL):longword;stdcall;

, mysql, mysql_errno()
API,
. 0 , .
MySQL errmsg.h.
mysqld_error.h.
MySQL
Docs/mysqld_error.txt.

. 0, .
6.3.12 mysql_error()
mysql_error(mysql:PMYSQL):pchar;stdcall;

, mysql, mysql_error()
API,
. , .
, :
if (mysql_errno(&mysql))

{
// an error occurred
}
if (mysql_error(&mysql)[0] != '\0')
{
// an error occurred
}


MySQL.
.

, . ,
.
6.3.13 mysql_escape_string()

mysql_real_escape_string() ,
. mysql_real_escape_string()
() ,
mysql_escape_string() charset.
6.3.14 mysql_fetch_field()
mysql_fetch_field(res:PMYSQL_RES):PMYSQL_FIELD;stdcall;


MYSQL_FIELD. ,
. mysql_fetch_field()
NULL, .
,
,
SELECT. , mysql_fetch_field()
mysql_field_seek().
mysql_fetch_field()

mysql_query() SELECT ,
mysql_store_result(), MySQL
blob (8K), mysql_fetch_field(),
BLOB. 8K , MySQL
BLOB.
-. , field.max_length

MYSQL_FIELD () . NULL,
.
6.3.15 mysql_fetch_fields()
mysql_fetch_fields(res:PMYSQL_RES):PMYSQL_FIELDS;stdcall;

MYSQL_FIELD .
.

MYSQL_FIELD .
6.3.16 mysql_fetch_field_direct()
mysql_fetch_field_direct(res:PMYSQL_RES;
fieldnr:integer):PMYSQL_FIELD;stdcall;

fieldnr ,
MYSQL_FIELD.
, . fieldnr
0 mysql_num_fields(result)-1.

MYSQL_FIELD .
6.3.17 mysql_fetch_lengths()
mysql_fetch_lengths(res:PMYSQL_RES):longword;stdcall;

()
. ,
, strlen().
, ,

, ,
strlen() ,
.
, NULL,
. , ,
mysql_fetch_row().

,
( ). NULL, - .


. NULL,
mysql_fetch_row() .
mysql_fetch_lengths()

6.3.18 mysql_fetch_row()
mysql_fetch_row(res:PMYSQL_RES):PMYSQL_ROW;stdcall;

.
mysql_store_result(), mysql_fetch_row() NULL,
, . mysql_use_result(),
mysql_fetch_row() NULL, , ,
.
mysql_num_fields(result). row
mysql_fetch_row(),
row[0] row[mysql_num_fields(result)-1]. NULL
NULL.
,
mysql_fetch_lengths(). , NULL 0.
, .
NULL, NULL, .

MYSQL_ROW . NULL, ,
, .


CR_SERVER_LOST

CR_UNKNOWN_ERROR

.
6.3.19 mysql_field_count()
mysql_field_count(mysql:PMYSQL):longword;stdcall;

MySQL , Version 3.22.24,


mysql_num_fields(res:PMYSQL_RES):longword;
stdcall;.

.
: mysql_store_result()
NULL (
). mysql_field_count(),
, mysql_store_result()
.
, , SELECT ( SELECT-).
, , .

, .
6.3.20 mysql_field_seek()
mysql_field_seek(res:PMYSQL_RES; offset:TMYSQL_FIELD_OFFSET):
TMYSQL_FIELD_OFFSET; stdcall;

.
mysql_fetch_field() ,
.
, 0 offset.

6.3.21 mysql_field_tell()
mysql_field_tell(res:PMYSQL_RES):longword;stdcall;

,
mysql_fetch_field().
mysql_field_seek().

.
6.3.22 mysql_free_result()
mysql_free_result(res:PMYSQL_RES);stdcall;

,
mysql_store_result(), mysql_use_result(), mysql_list_dbs()
. ,
, ,
mysql_free_result().
6.3.23 mysql_get_client_info()
mysql_get_client_info:pchar;stdcall;

, .

, MySQL.
6.3.24 mysql_get_host_info()
mysql_get_host_info(mysql:PMYSQL):pchar;stdcall;

, ,
.

, .
6.3.25 mysql_get_proto_info()
mysql_get_proto_info(mysql:PMYSQL):longword;stdcall;

, .

, ,
() .
6.3.26 mysql_get_server_info()
mysql_get_server_info(mysql:PMYSQL):pchar;stdcall;

, .

, .
6.3.27 mysql_info()
mysql_info(mysql:PMYSQL):pchar;stdcall;

,
, , .
mysql_info() NULL.
, .
: , .
INSERT INTO ... SELECT ...
: Records: 100 Duplicates: 0 Warnings: 0
INSERT INTO ... VALUES (...),(...),(...)...
: Records: 3 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ...
: Records: 1 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE

: Records: 3 Duplicates: 0 Warnings: 0


UPDATE

: Rows matched: 40 Changed: 40 Warnings: 0


, mysql_info() -NULL
INSERT ... VALUES ,
.

,
. NULL,
.
6.3.28 mysql_init()
mysql_init(mysql: PMYSQL):PMYSQL;stdcall;

MYSQL,
mysql_real_connect(). mysql NULL,
, .
, . mysql_init()
, ,
mysql_close().

MYSQL*. NULL, ,
.

NULL.
6.3.29 mysql_insert_id()
mysql_insert_id(mysql:PMYSQL):TMY_ULONGLONG;stdcall;

ID,
AUTO_INCREMENT. ,
INSERT , AUTO_INCREMENT.

, mysql_insert_id() 0,
AUTO_INCREMENT.
,
mysql_insert_id() , .
INSERT UPDATE,
AUTO_INCREMENT,
LAST_INSERT_ID(expr).
mysql_insert_id()

, SQL LAST_INSERT_ID()
AUTO_INCREMENT,
,
.

AUTO_INCREMENT,
. 0, ,
AUTO_INCREMENT.
6.3.30 mysql_kill()
mysql_kill(mysql:PMYSQL;pid:longword):integer;stdcall;

, , pid.

. , .

CR_COMMANDS_OUT_OF_SYNC

.
CR_SERVER_GONE_ERROR

MySQL .

CR_SERVER_LOST

.
CR_UNKNOWN_ERROR

.
6.3.31 mysql_list_dbs()
mysql_list_dbs(mysql:PMYSQL;const wild:pchar):PMYSQL_RES;stdcall;

, ,
,
wild. wild % _,
NULL, . mysql_list_dbs()
SHOW databases [LIKE wild].
mysql_free_result().

MYSQL_RES , NULL, .

CR_COMMANDS_OUT_OF_SYNC

CR_OUT_OF_MEMORY

.
CR_SERVER_GONE_ERROR

MySQL .

CR_SERVER_LOST

.
CR_UNKNOWN_ERROR

.
6.3.32 mysql_list_fields()
mysql_list_fields(mysql:PMYSQL;const table,wild:pchar):PMYSQL_RES;
stdcall;

, ,
,
wild. wild % _,
NULL, . mysql_list_fields()
SHOW COLUMNS FROM tbl_name [LIKE wild].
, , SHOW COLUMNS
FROM tbl_name mysql_list_fields().
mysql_free_result().

MYSQL_RES . NULL, .

CR_COMMANDS_OUT_OF_SYNC

CR_SERVER_GONE_ERROR

MySQL .
CR_SERVER_LOST

CR_UNKNOWN_ERROR

.
6.3.33 mysql_list_processes()
mysql_list_processes(mysql:PMYSQL):PMYSQL_RES;stdcall;

, .
, mysqladmin processlist
SHOW PROCESSLIST.
mysql_free_result().

MYSQL_RES . NULL, .

CR_COMMANDS_OUT_OF_SYNC

.
CR_SERVER_GONE_ERROR

MySQL .

CR_SERVER_LOST

.
CR_UNKNOWN_ERROR

.
6.3.34 mysql_list_tables()
mysql_list_tables(mysql:PMYSQL;const wild:pchar):PMYSQL_RES;stdcall;

, ,
,

wild. wild % _,
NULL, .
mysql_list_tables() SHOW tables [LIKE wild].
mysql_free_result().

MYSQL_RES . NULL, .

CR_COMMANDS_OUT_OF_SYNC

CR_SERVER_GONE_ERROR

MySQL .
CR_SERVER_LOST

CR_UNKNOWN_ERROR

.
6.3.35 mysql_num_fields()
mysql_num_fields(res:PMYSQL_RES):longword;stdcall;

.
,
.
, mysql_store_result() mysql_use_result()
NULL ( ).
mysql_field_count() ,
mysql_store_result() .
, ,
SELECT ( SELECT-). ,
, .

, .
6.3.36 mysql_num_rows()
mysql_num_rows(res:PMYSQL_RES):TMY_ULONGLONG;stdcall;

.
mysql_num_rows() ,
mysql_store_result() mysql_use_result(),
. mysql_store_result(), mysql_num_rows()
. mysql_use_result(),
mysql_num_rows() ,
.

.
6.3.37 mysql_options()
mysql_options(mysql: PMYSQL; option: TMYSQL_OPTION; const arg: pchar):
integer ;stdcall;

,
.
, .
mysql_options()
mysql_connect()

mysql_init(),
mysql_real_connect().

option , ,
arg . , arg
.
:

.
TMY_BOOL
.
,
TMY_BOOL MySQL
NT.
PCHAR
,
MySQL.

MYSQL_OPT_CONNECT_TIMEOUT longword
MYSQL_OPT_COMPRESS
MYSQL_OPT_NAMED_PIPE
MYSQL_INIT_COMMAND

MYSQL_READ_DEFAULT_FILE

PCHAR

MYSQL_READ_DEFAULT_GROUP PCHAR

.

my.cnf.

my.cnf
,
MYSQL_READ_DEFAULT_FILE.

, client ,
MYSQL_READ_DEFAULT_FILE MYSQL_READ_DEFAULT_GROUP.
:
connect_timeout
compress
database
debug
host
init-command
interactivetimeout
password
pipe
port
return-foundrows
socket
user

. Linux
.
-.
,
.
.
.
, MySQL.

, .
CLIENT_INTERACTIVE
mysql_real_connect().
.
,
MySQL, NT.
.
mysql_info() ,

UPDATE.
.
.

, timeout connect_timeout, timeout


.

. , .
6.3.38 mysql_ping()
mysql_ping(mysql:PMYSQL):integer;stdcall;

.
.
, ,
, ,
.

, . , .

CR_COMMANDS_OUT_OF_SYNC

CR_SERVER_GONE_ERROR

MySQL .
CR_UNKNOWN_ERROR

.
6.3.39 mysql_query()
mysql_query(mysql:PMYSQL; const q:pchar):integer;stdcall;

SQL, .
SQL.
(;) \g .
,
, mysql_real_query().
\0, mysql_query()
. ,
, mysql_field_count(),
.
mysql_query()

, . , .

CR_COMMANDS_OUT_OF_SYNC

CR_SERVER_GONE_ERROR

MySQL .
CR_SERVER_LOST

CR_UNKNOWN_ERROR

.
6.3.40 mysql_real_connect()
mysql_real_connect(mysql: PMYSQL; const host,user,passwd,db:pchar;
port:longword; const unix_socket:pchar;
clientflag:longword):PMYSQL;stdcall;

MySQL,
host. mysql_real_connect()
, API,
mysql_get_client_info().
mysql_real_connect()


TMYSQL. mysql_real_connect()
mysql_init(), TMYSQL.
mysql_options().
host IP. NULL
localhost, . OS
(Unix) (Windows),
TCP/IP,
.
user ID MySQL. user NULL,
. Unix ()
. Windows ODBC
!
passwd user. passwd NULL,
user, ,
.
MySQL ,
,
. :
mysql_real_connect():
.
db . db NULL,
.
port 0,
TCP/IP. , host
.

unix_socket NULL,
, . ,
host .
client_flag 0,
:


.
,
CLIENT_FOUND_ROWS
.

CLIENT_IGNORE_SPACE .
.
interactive_timeout (
CLIENT_INTERACTIVE wait_timeout )
.
db_name.tbl_name.col_name.
ODBC.
,
CLIENT_NO_SCHEMA
,

ODBC.
CLIENT_ODBC
ODBC.
CLIENT_SSL
SSL.
CLIENT_COMPRESS

MYSQL*, , NULL,
. , : ,
, NULL .

CR_CONN_HOST_ERROR

CR_CONNECTION_ERROR

.
CR_IPSOCK_ERROR

IP-.

CR_OUT_OF_MEMORY

.
CR_SOCKET_CREATE_ERROR

Unix-.

CR_UNKNOWN_HOST

IP- hostname.
CR_VERSION_ERROR


,
. ,
, ,
--old-protocol.
CR_NAMEDPIPEOPEN_ERROR

Windows.

CR_NAMEDPIPEWAIT_ERROR

Windows.
CR_NAMEDPIPESETSTATE_ERROR

Windows.

CR_SERVER_LOST
connect_timeout>

0 , connect_timeout ,
,
init-command, .

mysql_options(), MySQL
[client] your_prog_name my.cnf, ,
, - MySQL
.
, mysql_real_connect()
reconnect ( TMYSQL) 1.
, -
, .
6.3.41 mysql_real_escape_string()
mysql_real_escape_string(mysql:PMYSQL; wto:pchar; const wfrom:pchar;
wfromlength:longword):longword;stdcall;

, ,
SQL.
from SQL,
() .
to .
NUL (ASCII 0), \n, \r, \, ', ", Control-Z, .
, from length .
length*2+1 .
,
.
mysql_escape_string() , to .
: , .

, to, .
6.3.42 mysql_real_query()
mysql_real_query(mysql:PMYSQL; const q:pchar;
length:longword):integer;stdcall;

SQL, query,
length . SQL.
(`;') \g .
mysql_real_query() mysql_query()
, , ,
\0. , mysql_real_query() ,
mysql_query() , strlen().
, ,
mysql_field_count(), .

, . , .

CR_COMMANDS_OUT_OF_SYNC

CR_SERVER_GONE_ERROR

MySQL .
CR_SERVER_LOST

CR_UNKNOWN_ERROR

.
6.3.43 mysql_reload()
mysql_reload(mysql:PMYSQL):integer;stdcall;

, MySQL .
reload.

. , .

CR_COMMANDS_OUT_OF_SYNC

CR_SERVER_GONE_ERROR

MySQL .
CR_SERVER_LOST

CR_UNKNOWN_ERROR

.
6.3.44 mysql_row_seek()
mysql_row_seek(res:PMYSQL_RES;
offset:PMYSQL_ROW_OFFSET):PMYSQL_ROW_OFFSET;stdcall;


. ,
, mysql_row_seek()
mysql_store_result(), mysql_use_result().
, mysql_row_tell()
mysql_row_seek(). ,
, mysql_data_seek().

.
mysql_row_seek().
6.3.45 mysql_row_tell()
mysql_row_tell(res:PMYSQL_RES):PMYSQL_ROWS;stdcall;

()
mysql_fetch_row().
mysql_row_seek().
mysql_row_tell() mysql_store_result(),
mysql_use_result().

() .
6.3.46 mysql_select_db()
mysql_select_db(mysql:PMYSQL; const db:pchar):integer;stdcall;

, db,
, mysql.
,
.
,
, .
mysql_select_db()

. , .

CR_COMMANDS_OUT_OF_SYNC

.
CR_SERVER_GONE_ERROR

MySQL .

CR_SERVER_LOST

.
CR_UNKNOWN_ERROR

.
6.3.47 mysql_shutdown()
mysql_shutdown(mysql:PMYSQL):integer;stdcall;

.
(shutdown).

. , .

CR_COMMANDS_OUT_OF_SYNC

CR_SERVER_GONE_ERROR

MySQL .

CR_SERVER_LOST

.
CR_UNKNOWN_ERROR

.
6.3.48 mysql_stat()
mysql_stat(mysql:PMYSQL):pchar;stdcall;

, ,
mysqladmin status. uptime ,
, , .

, . NULL,
.

CR_COMMANDS_OUT_OF_SYNC

CR_SERVER_GONE_ERROR

MySQL .
CR_SERVER_LOST

CR_UNKNOWN_ERROR

.
6.3.49 mysql_store_result()
mysql_store_result(mysql:PMYSQL):PMYSQL_RES;stdcall;

mysql_store_result() mysql_use_result()
, (SELECT, SHOW, DESCRIBE, EXPLAIN).
mysql_store_result() mysql_use_result()
, ,
mysql_store_result() . , ...
, ,
mysql_store_result(). ,

, mysql_field_count() ,
.
mysql_store_result() ,
TMYSQL_RES .

,
( , , INSERT).
mysql_store_results()

,
. , ,
mysql_error() . mysql_errno() <>
0, mysql_field_count() <> 0, , .
mysql_store_results()

,
.
.
mysql_store_result() ,
, mysql_num_rows(), ,
.
mysql_fetch_row(),
, mysql_row_seek() mysql_row_tell(),
.
mysql_free_result()
.

MYSQL_RES . NULL, .

CR_COMMANDS_OUT_OF_SYNC

CR_OUT_OF_MEMORY

.
CR_SERVER_GONE_ERROR

MySQL .

CR_SERVER_LOST

.
CR_UNKNOWN_ERROR

.
6.3.50 mysql_thread_id()

mysql_thread_id(mysql:PMYSQL):longword;stdcall;

ID () .
mysql_kill(), .
, mysql_ping(), ID
. , ID
. ID .

ID () .
6.3.51 mysql_use_result()
mysql_use_result(mysql:PMYSQL):PMYSQL_RES;stdcall;

mysql_store_result() mysql_use_result()
, (SELECT, SHOW, DESCRIBE, EXPLAIN).
,
mysql_store_result(). ,
,
mysql_fetch_row().
, ,
,
mysql_store_result().
() ,
max_allowed_packet.
mysql_use_result()

, mysql_use_result()
,
, ^S
( ).
, .
mysql_use_result()
mysql_fetch_row() , NULL,

. API "Commands out of sync; You can't run
this command now", !

mysql_data_seek(), mysql_row_seek(),
mysql_row_tell(), mysql_num_rows() mysql_affected_rows() ,
mysql_use_result(),
, mysql_use_result(). , ,
, mysql_num_rows() .
mysql_free_result()
.

TMYSQL_RES. NULL, .

CR_COMMANDS_OUT_OF_SYNC

CR_OUT_OF_MEMORY

.
CR_SERVER_GONE_ERROR

MySQL .

CR_SERVER_LOST

.
CR_UNKNOWN_ERROR

.
6.4 API
6.4.1 mysql_query() mysql_store_result()
NULL?

, , :

malloc() (,
).
( ).
(, INSERT, UPDATE
DELETE).

,
, mysql_field_count(). mysql_field_count() ,
, ,
(, INSERT DELETE). mysql_field_count()
, .
mysql_error()
mysql_errno().

6.4.2 ?

, ,
:

,
INSERT, UPDATE DELETE.
: DELETE WHERE,
, !
mysql_affected_rows() .
mysql_num_rows() .
mysql_store_result() mysql_num_rows()
, mysql_store_result().
mysql_use_result() mysql_num_rows()
, mysql_fetch_row().
mysql_insert_id() ID, ,
AUTO_INCREMENT.
"6.3.126 mysql_insert_id()".
(LOAD DATA INFILE ..., INSERT INTO ... SELECT ...,
UPDATE) .
mysql_info(). mysql_info() NULL
.
mysql_affected_rows()

6.4.3 ID
?

, ,
AUTO_INCREMENT, ID
mysql_insert_id().
ID, LAST_INSERT_ID()
, mysql_query().
, AUTO_INCREMENT,
. , INSERT
AUTO_INCREMENT:
if (mysql_error(pmysql)[0]=0) && (mysql_num_fields(result)=0) &&
(mysql_insert_id(pmysql) != 0) then begin
used_id := mysql_insert_id(pmysql);
end;

ID .
. ,
AUTO_INCREMENT
( , NULL 0).

ID,
, SQL
:
INSERT INTO foo (auto,text)
VALUES(NULL,'text');
INSERT INTO foo2 (id,text)
VALUES(LAST_INSERT_ID(),'text');

# generate ID by inserting NULL


# use ID in second table

6.5 TmySQL 1.0.0.99XXXX


6.5.1

TmySQL , delphi
libmysql.dll. ,
.
6.5.2


Delphi.
libmysql.dll (Version 3.22.14-gamma,
).
6.5.3
unit MySql;
interface
uses classes, dialogs, sysutils;
type
TField = class
public
Name: String;
FieldType: String;
Constructor Create(aName: String);
end;
TFields = class
public
Constructor Create(res: pmysql_res);
Destructor Destroy; override;
Function Count: Integer;
Property Fields[Index: Integer]: TField read getField; default;
Procedure Add(Value: TField);
end;
TTable = class

public
Name: String;
Fields: TFields;
Constructor Create(aMySql: pmysql; aName: String);
Destructor Destroy; override;
end;
TTables = class
public
Constructor Create(aMySql: pmysql; aName: String);
Destructor Destroy; override;
Function Count: Integer;
Property Tables[Index: Integer]: TTable read getTable; default;
Procedure Add(Value: TTable);
end;
TDatabase = class
public
Name: String;
Selected: Boolean;
Tables: TTables;
Constructor Create(aMySql: pmysql; aName: String);
Destructor Destroy; override;
Function Select: Boolean;
end;
TDatabases = class
public
Constructor Create(aMySql: pmysql);
Destructor Destroy; override;
Function Count: Integer;
Property Databases[Index: Integer]: TDatabase
read getDatabase; default;
Procedure Add(Value: TDatabase);
end;
TRow = class
public
Constructor Create(aRow: TStringList);
Destructor Destroy; override;
Function Count: Integer;
Property Databases[Index: Integer]: String read getValue; default;
Procedure Add(Value: String);
end;
TRows = class
public
Constructor Create(res: pmysql_res; Count: Integer);
Destructor Destroy; override;
Function Count: Integer;
Property Rows[Index: Integer]: TRow read getRow; default;
Procedure Add(Value: TRow);
end;
TResult = class
public
Rows: TRows;
Fields: TFields;
AffectedRows: Integer;
Constructor Create(res: pmysql_res; aMySql: pmysql);
Destructor Destroy; override;
Function lastError: String;

end;
TMySql = class
public
class function ClientVersion: String;
constructor CreateConnect(aHost, aUser, aPassword: String;
aPort: Integer);
destructor Destroy; override;
function Connect: Boolean;
function Disconnect: Boolean;
function Connected: boolean;
Property Name: String read getName write setName;
Property Host: String read getHost write setHost;
Property User: String read getUser write setUser;
Property Password: String read getPassword write setPassword;
Property Port: Integer read getPort write setPort;
function getVersion: String;
function getHostInfo: String;
function getProtocolVersion: Integer;
function getThreadId: Longint;
function getStat: String;
function getProcesses: TResult;
function getDatabases: TDatabases;
function Query(sql: String): TResult;
function SelectDb(d: String): Boolean;
function CreateDb(name: String): Boolean;
function DeleteDb(name: String): Boolean;
function RefreshGrants: Boolean;
end;

6.5.4

, - :
TmySQL. .
TmySQL, Create CreateConnect,
.
TmySQL.getDatabases : TDatabases, TDatabase, TTables, TTable, TFields,
TField.
TmySQL.Query TmySQL.getProcesses : TResult, TFields, TField,
TRows, TRow, String.
6.5.5 Copyright

freeware, for personal use.


US$ 20 . ,
.
:

Hillware I/S
Dennis Thryse
Solvangsvej 6, st, th
DK-9000 Aalborg
mailto:qabi@mindless.com
http://members.xoom.com/qabi

This product is:


Copyright 1999 by Hillware I/S, Dennis Thryse

Microsoft SQL Server 2005


Oracle