Go to the first, previous, next, last section, table of contents.


MySQL クライアントツールと API

MySQL C API

C API は MySQL で配布されます。それは libmysqlclient ライブラリに含まれます。データベースへのアクセスに C プログラムを許します。

他のクライアント API の多く(Java を除く全て)は、このライブラリを接続に使 用します。そして例えば、同じ環境変数を使用できます。

クライアントは最大通信バッファサイズを持ちます。これは自動的に増加する最 大サイズ(デフォルトは 512kb)です。バッファは要求に応じて増加する(しかし close まで減少しない)ので、これを増加させても資源は取られません。このサ イズチェックは主に間違ったクエリと通信パケットのためのチェックです。

通信バッファは一つの SQL ステートメントと、返されるデータの1行を含むのに 十分大きくなくてはいけません(もちろん同時にではありません)。各スレッドの 通信バッファは、任意の行やクエリのために指定された制限まで、動的に増大し ます。

最大 16M のデータを含む BLOB を持っている場合は、少なくとも 16M を通信バッファ制限にしなくてはいけません。 「MySQL のバッファサイズの変更方法」節参照 。

MySQL は、クエリ後に各接続バッファを net_buffer_length に縮小しま す。

mysql_affected_rows 最後の UPDATE, DELETE または INSERT によって影響された行数を取り出します。
mysql_close サーバ接続をクローズします。
mysql_connect MySQL サーバへの接続を確立します。
mysql_create_db データベースを生成します。
mysql_data_seek クエリ結果セットから任意の行にシークします。
mysql_drop_db データベースを破棄します。
mysql_eof 最後の行が読まれたかどうかを判定します。
mysql_escape_string SQL ステートメントのために文字列をエスケープします。 「リテラル。文字列と数値をどのように書くか?」節参照
mysql_error 最後の MySQL 関数からのエラーメッセージ。
mysql_fetch_field テーブル項目の型を見つけ出します。
mysql_fetch_lengths クエリ結果セット中の全ての項目の長さを返します。
mysql_fetch_row クエリ結果から '次の' 行を取り出します。
mysql_field_seek 項目番号項目上に項目カーソルを置きます。
mysql_free_result クエリ結果を格納するために使用されたメモリを解放します。
mysql_get_client_info 現在のクライアントライブラリのバージョン情報を返します。
mysql_get_host_info サーバホストの名前を返します。
mysql_get_proto_info 接続に使用されるプロトコルバージョンを得ます。
mysql_get_server_info サーバのバージョン番号を返します。
mysql_insert_id AUTO_INCREMENT 項目に生成された ID を返します。
mysql_list_dbs 適合するデータベース名を返します。
mysql_list_fields 適合する項目名を返します。
mysql_list_processes 現在のサーバスレッドのリストを得ます。
mysql_list_tables 適合するテーブルの名前を返します。
mysql_num_fields 結果セット中の項目の数を返します。
mysql_num_rows 結果セット中の行の数を返します。
mysql_query SQL クエリを実行します。
mysql_real_query 長さ情報を伴う SQL クエリを実行します。
mysql_reload サーバのユーザパーミッションテーブルを再ロードします。
mysql_select_db データベースに接続します。
mysql_shutdown データベースサーバをシャットダウンします。
mysql_stat 文字列でサーバ状態を返します。
mysql_store_result クライアントに結果セットを読み込みます。
mysql_use_result 各行の動的な結果セットを始めます。これは mysql_store_result() よ りもとても少ないメモリを使用しますが、サーバにより多くの strain を与えま す。
int mysql_affected_rows(MYSQL *mysql)
最後の UPDATE, DELETE または INSERT によって影響された行数を取り出します。
void mysql_close(MYSQL *mysql)
サーバ接続をクローズします。
MYSQL *mysql_connect(MYSQL *mysql, const char *host, const char *user, const char *passwd)
MySQL サーバへの接続を確立します。
int mysql_create_db(MYSQL *mysql, const char *db)
データベースを生成します。
void mysql_data_seek(MYSQL_RES *res, uint offset)
クエリ結果セットから任意の行にシークします。
int mysql_drop_db(MYSQL *mysql, const char *db)
データベースを破棄します。
int mysql_eof(MYSQL_RES *)
最後の行が読まれたかどうかを判定します。
char *mysql_error(MYSQL *mysql)
最後の MySQL 関数からのエラーメッセージ。
uint mysql_escape_string(char *to,char *from,uint length)
SQL ステートメントのために文字列をエスケープします。
MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *handle)
テーブル項目の型を見つけ出します。 結果を取り出さないで BLOB の長さをクエリすると、MySQL は 'default blob length' を返します。これは 8192 です。テーブルの検索を行っ た時。結果を取り出す時、column_object->max_length は、個々のクエリの実際 の max_length を含みます。 MySQLBLOB の最大長を知らないため、8192 サイズが選択 されます。これはいつかコンフィグ可能になるべきです。
unsigned int *mysql_fetch_lengths(MYSQL_RES *mysql)
クエリ結果セット中の全ての項目の長さを返します。
MYSQL_ROW mysql_fetch_row(MYSQL_RES *mysql)
クエリ結果から '次の' 行を取り出します。
void mysql_field_seek(MYSQL_RES *result, int field)
項目番号項目上に項目カーソルを置きます。
void mysql_free_result(MYSQL_RES *result)
クエリ結果を格納するために使用されたメモリを解放します。
char *mysql_get_client_info(void)
現在のクライアントライブラリのバージョン情報を返します。
char *mysql_get_host_info(MYSQL *mysql)
サーバホストの名前を返します。
int mysql_get_proto_info(MYSQL *mysql)
接続に使用されるプロトコルバージョンを得ます。
char *mysql_get_server_info(MYSQL *mysql)
サーバのバージョン番号を返します。
unsigned long mysql_insert_id(MYSQL *mysql)
AUTO_INCREMENT 項目に生成された ID を返します。API は unsigned long を返 すため、これを BIGINT 項目で使用できません。この場合、 LAST_INSERT_ID() SQL 関数を使用する必要があります。
MYSQL_RES *mysql_list_dbs(MYSQL *mysql, const char *wild)
適合するデータベース名を返します。
MYSQL_RES *mysql_list_fields(MYSQL *mysql, const char *table, const char *wild)
適合する項目名を返します。
MYSQL_RES *mysql_list_processes(MYSQL *mysql)
現在のサーバスレッドのリストを得ます。
MYSQL_RES *mysql_list_tables(MYSQL *mysql, const char *wild)
適合するテーブルの名前を返します。
int mysql_num_fields(MYSQL_RES *result)
結果セット中の項目の数を返します。
int mysql_num_rows(MYSQL_RES *result)
結果セット中の行の数を返します。
int mysql_query(MYSQL *mysql, const char *query)
SQL クエリを実行します。
int mysql_real_query(MYSQL *mysql, const char *query, uint length)
長さ情報を伴う SQL クエリを実行します。
int mysql_reload(MYSQL *mysql)
サーバのユーザパーミッションテーブルを再ロードします。
int mysql_select_db(MYSQL *mysql, const char *db)
データベースに接続します。
int mysql_shutdown(MYSQL *mysql)
データベースサーバをシャットダウンします。
char *mysql_stat(MYSQL *mysql)
文字列でサーバ状態を返します。
MYSQL_RES *mysql_store_result(MYSQL *mysql)
クライアントに結果セットを読み込みます。
MYSQL_RES *mysql_use_result(MYSQL *mysql)
各行の動的な結果セットを始めます。

mysql_query() が成功して復帰した後、mysql_store_result() が NULL を返す時があるのは何故?

これは次の一つを意味します:

  1. Malloc が失敗した。
  2. データが読めなかった (接続時のエラー)。
  3. ステートメントがデータを返さないステートメント (INSERT または UPDATE または DELETE) だった。

ステートメントが与えられた結果を持つかどうかは、 mysql_num_fields(MYSQL *) が 0 でないことをチェックすることで、 常にチェックできます。これが 0 なら、最後のクエリは値を返さないステート メントです。例えば INSERTDELETE

mysql_error(MYSQL *) が空でない場合はエラーです!

クエリから得られる結果は何か?

mysql_affected_rows(MYSQL *) は、INSERT, UPDATE ま たは DELETE を行なった時の最後のクエリで、影響された行数を返しま す。ただし、WHERE 節がない DELETE が使用されて、テーブルが 切り詰められた場合は例外です。これはとても速いです! この場合、影響され た行数は 0 として返されます。

AUTO_INCREMENT インデックスを持つテーブルに行を挿入した時、 mysql_insert_id(MYSQL *) は最後のクエリで与えられた ID を返します。 「最後に挿入された行のユニーク ID をどのように得られるか?」節参照

一部のクエリ、LOAD DATA INFILE...INSERT INTO ... SELECT ..., UPDATE は追加の情報を返します。この結果は mysql_info(MYSQL *) で返されます。mysql_info() は追加情報 がない場合は null ポインタを返します。

最後に挿入された行のユニーク ID をどのように得られるか?

AUTO_INCREMENT キーを持つレコードを挿入すると、 mysql_insert_id(MYSQL *) で与えられた ID が得られます。

最後の値はサーバ内にも格納され、LAST_INSERT_ID() 関数で取り出せま す。

次のコードで、auto_increment インデックスが使用されたかどうかチェックで きます。これは、クエリが auto_increment インデックスを伴う INSERT かどうかもチェックできます。

if (mysql_error(MYSQL)[0] == 0 &&
    mysql_num_fields(MYSQL_RESULT) == 0 &&
    mysql_insert_id(MYSQL) != 0)
  used_id = mysql_insert_id(MYSQL);

LAST_INSERT_ID() が返す id はサーバで接続毎に管理されます。他のク ライアントによっておかしくなることはありません。他の auto_increment 項目を 非マジック値 (非 NULL または 非 0) で更新した場合でも、それは変更されま せん。

What is the difference between mysql_use_result() and mysql_store_result() modes?

mysql_use_resulys はサーバからの結果を、一時テーブルやローカルバッ ファに格納することなく、直接読み込みます。これは mysql_store_result よりもいくらか速くなり、より少ないメモリを使用 します。クライアント側で各行に行なう多くの処理がある場合、またはユーザが ^S (stop scroll) を行なうような画面に出力を送る場合は、 mysql_use_results を使用すべきではありません。これを行なうと、サー バとタイアップし、他のスレッドは使用中のテーブルを更新できなくなります。 mysql_use_result 使用時は mysql_data_seek mysql_num_rows の使用や他のクエリの発行ができません。

mysql_use_result 使用時、NULL ポインタを得るまで mysql_fetch_row() を実行する必要があります。そうでなければ次のク エリは前のクエリからの結果を得るためです。これを行うことを忘れた場合、C API はエラーを与えます! Commands out of sync; You can't run this command now

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

これは、あなたのシステム上では、コンパイル/リンク行の最後で、math ライブ ラリ (-lm) を含める必要があることを意味します。

スレッド安全クライアントを作る方法

クライアントは 'ほとんど' スレッド安全です。一番大きな問題は net.c (ソケッ トから読み込みをするサブルーチン) が割り込みに対して安全でないことです。 これは、サーバからの長い読み込みを中断できるように、自身のアラームを持ち たいだろうという考慮からです。

標準クライアントライブラリはスレッドオプションでコンパイルされていません。

スレッド安全クライアントを得るためには、-lmysys, -lstring-ldbug ライブラリとサーバが使用する net_serv.o を使用し ます。

スレッドクライアントを使用する時、thr_alarm.c ルーチンを大いに使用できる と私は考えます。mysys ルーチンを使用する場合、覚えておくべきたった一つの ことは my_init() を最初に呼ぶことです!

スレッド安全クライアントの作成

mysql_connect() を除く全ての関数は現在スレッド安全です。

スレッド安全を得るためには次を行ないます:

クライアントを次で再コンパイル:

CPPFLAGS=-DTHREAD_SAFE_CLIENT ./configure ...

いくつかのエラーが出ます。標準クライアントのリンク時の未定義シンボルのた めです。pthread ライブラリがデフォルトでは含められていないので。

結果の libmysqld.a ライブラリはスレッド安全です。

2つのスレッドは同じハンドル (mysql_connect() で返される) を同時に 使用できません。2つのスレッドが、mysql_store_result() で作成され た異なる MYSQL_RES ハンドルを使用できるとしてもです。

スレッドクライアントを使用する時、thr_alarm.c ルーチンを大いに使用できま す。mysys ルーチンを使用する場合に、覚えておく必要があることは、 my_init() を最初に呼ぶことだけです!

MySQL Perl API

Since DBI/DBD now is the recommended perl interface mysqlperl is not documented here.

DBI with DBD::mysql

DBI is a generic interface for many databases. That means that you can write a script what works with many different database engines without change. You need a DataBase Driver (DBD) defined for each database type. For MySQL, this driver is called DBD::mysql.

For more information on the Perl5 DBI, please visit DBIs web page and read the documentation. For more information on Object Oriented Programming (OOP) as defined in Perl5, see the perl OOP page.

The DBI interface

Portable DBI methods.

connect Establish a connection to a database server
prepare Get a SQL statement ready for execution
do Prepares and executes a SQL statement
disconnect Disconnect from the database server
quote Quote strings/blobs to be inserted
execute Executes prepared statements
fetchrow_array fetch the next row as an array of fields.
fetchrow_arrayref fetch next row as a reference array of fields
fetchrow_hashref fetch next row as a reference to a hashtable
fetchall_arrayref Get all data as a array of arrays
finish finish a statment and let the system free resources
rows Returns the number of rows affected
data_sources Return an array of databases available on localhost
ChopBlanks Shall fetchrow trim spaces
NUM_OF_PARAMS Number of placeholders in the prepared statement
NULLABLE Which columns can be NULL
MySQL specific methods.
insertid The latest auto_increment value
is_blob Which column ar BLOBs
is_key Which columns are keys
is_num Which columns are numeric
is_pri_key Which columns are primary keys
is_not_null Which columns can NOT be NULL. See NULLABLE
length Maximum theoretically possible column sizes
max_length Maximum physical present column sizes
NAME Column names
NUM_OF_FIELDS Number of fields returned.
table Table names in returned set
type All coulumn types
_CreateDB Create a database
_DropDB Drop a database. THIS IS DANGEROUS
connect
You use the connect method to make a database connection to the data source. The $data_source value should begin with DBI:driver_name:. Example connect methods with the DBD::mysql driver:
$dbh = DBI->connect("DBI:mysql:$database", $user, $password);
$dbh = DBI->connect("DBI:mysql:$database:$hostname",
                    $user, $password);
$dbh = DBI->connect("DBI:mysql:$database:$hostname:$port",
                    $user, $password);
If the username and/or password are undefined, then the DBI will use the values of the DBI_USER, DBI_PASS environment variables respectively. If you don't specify a hostname, then it will default to "localhost". If you don't specify a port, then it defaults to the default mysql port (3306).
prepare
Prepare gets a SQL statement ready for execution by the database engine and returns a statement handle ($sth) which invokes the execute method. Example:
$sth = $dbh->prepare($statement) or die "Can't prepare $statement: 
$dbh->errstr\n";
do
The "do" method prepares and executes a SQL statement and returns the number of rows effected. This method is generally used for "non-select" statements which can not be prepared in advance (driver limitation) or which do not need to executed more than once (inserts, deletes, etc.). Examples:
$rc = $dbh->do($statement) or
        die "Can't execute $statement: $dbh- >errstr\n";
disconnect
Disconnect will disconnect the database handle from the database. This is typically called right before you exit from the program. Example:
$rc = $dbh->disconnect;
quote
The quote method is used to "escape" any special characters contained in the string and to add the required outer quotation marks.
$sql = $dbh->quote($string)
execute
This method executes the prepared statement. For non-select satements, it returns the number of rows affected. For select statements, execute only starts the SQL query in the database. You need to use one of the fetch_* methods below to retrieve the data. Example:
$rv = $sth->execute or die "can't execute the query: $sth->errstr;
fetchrow_array
This method "fetches" the next row of data and returns it as an array of field values. Example:
while(@row = $sth->fetchrow_array) {
        print qw($row[0]\t$row[1]\t$row[2]\n); 
}
fetchrow_arrayref
This method "fetches" the next row of data and returns it as a reference to an array of field values. Example:
while($row_ref = $sth->fetchrow_arrayref) {
        print qw($row_ref->[0]\t$row_ref->[1]\t$row_ref->[2]\n);
}
fetchrow_hashref
This method fetches a row of data and returns a reference to a hash table containing field name/value pairs. This method is not nearly as efficient as using array references as demonstrated above. Example:
while($hash_ref = $sth->fetchrow_hashref) {
        print qw($hash_ref->{firstname}\t$hash_ref->{lastname}\t\
                $hash_ref- > title}\n);
}
fetchall_arrayref
This method is used to get all the data (rows) to be returned from the SQL statement. It returns a reference to an array of arrays of references to each row. You access/print the data by using a nested loop. Example:
my $table = $sth->fetchall_arrayref or die "$sth->errstr\n";
my($i, $j);
for $i ( 0 .. $#{$table} ) {
        for $j ( 0 .. $#{$table->[$i]} ) {
                print "$table->[$i][$j]\t";
        }
        print "\n";
}
finish
Indicates that no more data will be fetched from this statement handle. You call this method to free up the statement handle and any system resources it may be holding. Example:
$rc = $sth->finish;
rows
Returns the number of rows affected (updated, deleted, etc.) from the last command. This is usually used after a do() or non-select execute() statement.
$rv = $sth->rows;
NULLABLE
A reference to an array of boolean values; TRUE indicates that this column may contain NULLs.
$null_possible = $sth->{NULLABLE}; 
NUM_OF_FIELDS
Number of fields returned by a SELECT or LISTFIELDS statement. You may use this for checking whether a statement returned a result: A zero value indicates a non-SELECT statement like INSERT, DELETE or UPDATE.
$nr_of_fields = $sth->{NUM_OF_FIELDS};
data_sources
This method returns an array of databases available to the mysql daemon on localhost.
@dbs = DBI->data_sources("mysql"); 
ChopBlanks
This determines whether a fetchrow will chop preceding and trailing blanks off the returned values.
$sth->{'ChopBlanks') =1; 
MySQL specific methods.
insertid
If you use the auto-increment feature of mysql, the new auto-incremented values will be stored here.
$new_id = $sth->{insertid};
is_blob
Reference to an array of boolean values; TRUE indicates that the respective column is a blob.
$keys = $sth->{is_blob};
is_key
Reference to an array of boolean values; TRUE indicates, that the respective column is a key.
$keys = $sth->{is_key};
is_num
Reference to an array of boolean values; TRUE indicates, that the respective column contains numeric values.
$nums = $sth->{is_num};
is_pri_key
Reference to an array of boolean values; TRUE indicates, that the respective column is a primary key.
$pri_keys = $sth->{is_pri_key};
is_not_null
A reference to an array of boolean values; FALSE indicates that this column may contain NULLs. You should better use the NULLABLE attribute above which is a DBI standard.
$not_nulls = $sth->{is_not_null};
max_length
length
A reference to an array of maximum column sizes. The max_length is the maximum physically present in the result table, length gives the theoretically possible maximum.
$max_lengts = $sth->{max_length};
$lengts = $sth->{length};
NAME
A reference to an array of column names.
$names = $sth->{NAME};
table
Returns a reference to an array of table names.
$tables = $sth->{table};

More DBI/DBD information

You can use the perldoc command to get more information about DBI.

perldoc DBI
perldoc DBI::FAQ
perldoc mysql

You can also use the pod2man, pod2html, etc.. tools to translate to other formats.

And of course you can find the latest DBI information at the DBI web page
.

MySQL Java connectivity (JDBC)

Insert pointers/descriptions of JDBC.

MySQL PHP API's

PHP documentation

MySQL C++ API's

Insert pointers/descriptions for C++.

MySQL Python API's

Insert pointers/descriptions for Python.

MySQL TCL API's

Insert pointers/descriptions for TCL.


Go to the first, previous, next, last section, table of contents.