This chapter describes the APIs available for MySQL, where to get them, and how to use them. The C API is the most extensively covered, as it was developed by the MySQL team, and is the basis for most of the other APIs.
PHP is a server-side, HTML-embedded scripting language that may be used to create dynamic web pages. It contains support for accessing several databases, including MySQL. PHP may be run as a separate program or compiled as a module for use with the Apache web server.
The distribution and documentation are available at the PHP web site (http://www.php.net/).
-lz
last when linking
with -lmysqlclient
.
ここでは Perl DBI
インターフェースについて述べる。
以前のインターフェースは mysqlperl
であった。
DBI
/DBD
が Perl インターフェースとして現在推奨されているので、
mysqlperl
に関してはここでは述べない。
DBI
with DBD::mysql
DBI
は多くのデーターベースとの一般的なインターフェースである。
これは、多くのデーターベースと動作するスクリプトを変更なしに書けることを意味する。
そのためには、それぞれのデータベース用のデータベースドライバ (DBD) が必要である。
MySQL では、そのドライバは DBD::mysql
である。
Perl5 DBI に関する詳細は、DBI
ウェッブページを参照のこと:
http://dbi.perl.org/
Object Oriented Programming (OOP) に関する詳細は、Perl OOP ページを参照のこと:
http://language.perl.com/info/documentation.html
Note that if you want to use transactions with Perl, you need to have
Msql-Mysql-modules
version 1.2216 or newer.
The recommended Perl module is DBD-mysql-2.1022
or newer.
Installation instructions for MySQL Perl support are given in 「2.7 Perl Installation Comments」節.
If you have the MySQL module installed, you can find information about specific MySQL functionallity with one of the following command
shell>perldoc DBD/mysql
shell>perldoc mysql
DBI
InterfacePortable DBI Methods
connect | データベースサーバと接続する |
disconnect | データベースサーバとの接続を切る |
prepare | SQL文を設定する |
execute | 設定されたSQL文を実行する |
do | SQL文を設定し、実行する |
quote | 挿入するためのクォート文字、または BLOB 値
|
fetchrow_array | フィールドの配列として次のレコードを取り出す |
fetchrow_arrayref | フィールドの配列参照として次のレコードを取り出す |
fetchrow_hashref | ハッシュテーブルへの参照として次のレコードを取り出す |
fetchall_arrayref | 配列の配列として全データを取り出す |
finish | 命令を終了し、リソースからシステムを切り離す |
rows | 影響のあったレコードの数を返す |
data_sources | ローカルホスト上で利用できるデータベースの配列を返す |
ChopBlanks | fetchrow_* メソッドが空白を取り除くかどうかを管理する
|
NUM_OF_PARAMS | 設定された命令文中の placeholder の数 |
NULLABLE | どのフィールドに NULL 値があるか?
|
trace | Perform tracing for debugging |
MySQL 固有メソッド
insertid | 最後の AUTO_INCREMENT 値
|
is_blob | どのフィールドが BLOB か?
|
is_key | どのフィールドがキーか? |
is_num | どのフィールドが数値型か? |
is_pri_key | どのフィールドがプライマリキーか? |
is_not_null | どのフィールドが NULL 値か? NULLABLE 参照。
|
length | 利用可能なフィールドサイズの最大値 |
max_length | 実際に存在しているフィールドサイズの最大値 |
NAME | フィールド名 |
NUM_OF_FIELDS | 返されたフィールドの数 |
table | 返されたセットのテーブル名 |
type | 全てのフィールドの型 |
_CreateDB | データベースを作成する |
_DropDB | データベースを削除する。 ***このメソッドは危険である*** |
以下の節に、より詳細な Perl メソッドの解説がある。 Variables used for method return values have these meanings:
$dbh
$sth
$rc
$rv
汎用 DBI メソッド
connect($data_source, $username, $password)
connect
を使う。
$data_source
値は DBI:driver_name:
ではじめること。
DBD::mysql
ドライバーを用いた connect
の使用例:
$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);ユーザー名またはパスワードが未設定の場合、
DBI
は環境変数である
DBI_USER
と DBI_PASS
をそれぞれ使う。
ホスト名を指定しない場合は、'localhost'
がデフォルトとなる。
ポート番号を指定しない場合は、MySQL ポート(3306)
がデフォルトとなる。
As of Msql-Mysql-modules
Version 1.2009,
the $data_source
value allows certain modifiers:
mysql_read_default_file=file_name
mysql_read_default_group=group_name
[client]
group. By specifying the mysql_read_default_group
option, the default group becomes the [group_name]
group.
mysql_compression=1
mysql_socket=/path/to/socket
DBI
script, you can take them from the user's `~/.my.cnf'
option file instead by writing your connect
call like this:
$dbh = DBI->connect("DBI:mysql:$database" . ";mysql_read_default_file=$ENV{HOME}/.my.cnf", $user, $password);This call will read options defined for the
[client]
group in the
option file. If you wanted to do the same thing but use options specified
for the [perl]
group as well, you could use this:
$dbh = DBI->connect("DBI:mysql:$database" . ";mysql_read_default_file=$ENV{HOME}/.my.cnf" . ";mysql_read_default_group=perl", $user, $password);
disconnect
disconnect
メソッドは、データベースとのデータベースハンドルを切断する。
プログラムを終了する直前に呼び出されるのが典型的である。
例:
$rc = $dbh->disconnect;
prepare($statement)
execute
メソッドで
使用出来るステートメントハンドル ($sth)
を返す。
Typically you handle SELECT
statements (and SELECT
-like
statements such as SHOW
, DESCRIBE
, and EXPLAIN
) by
means of prepare
and execute
. Example:
$sth = $dbh->prepare($statement) or die "Can't prepare $statement: $dbh->errstr\n";If you want to read big results to your client you can tell Perl to use
mysql_use_result()
with:
my $sth = $dbh->prepare($statement { "mysql_use_result" => 1});
execute
execute
メソッドは、設定されたSQL文を実行する。非 SELECT
文のときは、
影響のあったレコードの数を返す。 もしなんの変化もなかったなら、 execute
は "0E0"
(これは Perl では ゼロ 扱いですが、 真 でもある) を返す。
If an error occurs, execute
returns undef
.
SELECT
文のときは、SQL要求を開始するのみである。
データを操作する fetch_*
メソッドの内の一つを記述する必要がある。
例:
$rv = $sth->execute or die "can't execute the query: $sth->errstr;
do($statement)
do
メソッドはSQL文を設定・実行し、影響のあったレコードの数を返す。
このメソッドは、「非 select」文、すなわち、高度(ドライバーの限界のため)で設定できない文、
一度の実行(inserts, deletes など)で済む文のときに一般的に用いられる。
例:
$rv = $dbh->do($statement) or die "Can't execute $statement: $dbh- >errstr\n";
quote($string)
quote
メソッドは、文字列中にエスケープ文字があるときに用いられ、
クォート文字を文の外側に付加する。
例:
$sql = $dbh->quote($string)
fetchrow_array
while(@row = $sth->fetchrow_array) { print qw($row[0]\t$row[1]\t$row[2]\n); }
fetchrow_arrayref
while($row_ref = $sth->fetchrow_arrayref) { print qw($row_ref->[0]\t$row_ref->[1]\t$row_ref->[2]\n); }
fetchrow_hashref
fetchrow_arrayref
)よりもかなり効率的ではない。例:
while($hash_ref = $sth->fetchrow_hashref) { print qw($hash_ref->{firstname}\t$hash_ref->{lastname}\t\ $hash_ref- > title}\n); }
fetchall_arrayref
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
$rc = $sth->finish;
rows
do
あるいは 非 SELECT
execute
文を
実行した後に、たいてい使われる。例:
Example:
$rv = $sth->rows;
NULLABLE
NULL
values.
The possible values for each array element are 0 or the empty string if the
column cannot be NULL
, 1 if it can, and 2 if the column's NULL
status is unknown.
Example:
$null_possible = $sth->{NULLABLE};
NUM_OF_FIELDS
SELECT
文や SHOW FIELDS
文によって返された
フィールドの数を示している。命令文が結果を返したかどうかをチェックするのに、
これを使うことが出来る:0値は、INSERT
, DELETE
または
UPDATE
のような非 SELECT
文を示している。例:
Example:
$nr_of_fields = $sth->{NUM_OF_FIELDS};
data_sources($driver_name)
'localhost'
ホスト上の MySQL サーバで
利用可能なデータベースの名前を含んだ配列を返す。例:
@dbs = DBI->data_sources("mysql");
ChopBlanks
fetchrow_*
メソッドが返り値から前後の空白を
除去するかどうかを決定する。例:
$sth->{'ChopBlanks'} =1;
trace($trace_level)
trace($trace_level, $trace_filename)
trace
method enables or disables tracing. When invoked as a
DBI
class method, it affects tracing for all handles. When invoked as
a database or statement handle method, it affects tracing for the given
handle (and any future children of the handle). Setting $trace_level
to 2 provides detailed trace information. Setting $trace_level
to 0
disables tracing. Trace output goes to the standard error output by
default. If $trace_filename
is specified, the file is opened in
append mode and output for all traced handles is written to that
file. Example:
DBI->trace(2); # trace everything DBI->trace(2,"/tmp/dbi.out"); # trace everything to # /tmp/dbi.out $dth->trace(2); # trace this database handle $sth->trace(2); # trace this statement handleYou can also enable
DBI
tracing by setting the DBI_TRACE
environment variable. Setting it to a numeric value is equivalent to calling
DBI->(value)
. Setting it to a pathname is equivalent to calling
DBI->(2,value)
.
MySQL 固有メソッド
The methods shown here are MySQL-specific and not part of the
DBI
standard. Several of them are now deprecated:
is_blob
, is_key
, is_num
, is_pri_key
,
is_not_null
, length
, max_length
, and table
.
Where DBI
-standard alternatives exist, they are noted here:
insertid
AUTO_INCREMENT
を使うとき、
新しい自動繰り上がり値がここに記憶される。例:
Example:
$new_id = $sth->{insertid};As an alternative, you can use
$dbh->{'mysql_insertid'}
.
is_blob
BLOB
値であることを示す。例:
$keys = $sth->{is_blob};
is_key
$keys = $sth->{is_key};
is_num
$nums = $sth->{is_num};
is_pri_key
$pri_keys = $sth->{is_pri_key};
is_not_null
NULL
値を含むことを示す。
例:
$not_nulls = $sth->{is_not_null};
is_not_null
is deprecated;
前述の NULLABLE
属性を使用するほうが望ましい。それが DBI の標準である。
length
max_length
length
配列は、
(テーブル記述で定義された)各フィールドの利用可能最大値を示す。
max_length
配列は、テーブル中に実際に存在している最大値を示す。例:
$lengths = $sth->{length}; $max_lengths = $sth->{max_length};
NAME
$names = $sth->{NAME};
table
$tables = $sth->{table};
type
$types = $sth->{type};
DBI
/DBD
に関するそれ以上の情報
DBI
に関するそれ以上の情報は perldoc
コマンドで得られる。
perldoc DBI perldoc DBI::FAQ perldoc DBD::mysql
他のフォーマットに変換するツール、pod2man
, pod2html
なども
使うことが出来る。
そしてもちろん、DBI
の最新情報は DBI
ウェッブページで見ることが出来る:http://dbi.perl.org/.
MySQL は MyODBC
プログラムで ODBC 機能を提供します。
This chapter will teach you how to install MyODBC
,
and how to use it. Here, you will also find a list of common programs that
are known to work with MyODBC
.
MyODBC
2.50 is a 32-bit ODBC 2.50 specification level 0 (with
level 1 and level 2 features) driver for connecting an ODBC-aware
application to MySQL. MyODBC
works on Windows 9x/Me/NT/2000/XP
and most Unix platforms.
MyODBC
3.51 is an enhanced version with ODBC 3.5x specification
level 1 (complete core API + level 2 features).
MyODBC
は Open Source
で、最新の物は以下にあります:
http://www.mysql.com/downloads/api-myodbc.html.
Please note that the 2.50.x versions are LGPL
licensed,
whereas the 3.51.x versions are GPL
licensed.
日本語文字コードに対応させた物は: http://www.SoftAgency.co.jp/.
If you have problem with MyODBC
and your program also works
with OLEDB, you should try the OLEDB driver.
Normally you only need to install MyODBC
on Windows machines.
You only need MyODBC
for Unix if you have a program like
ColdFusion that is running on the Unix machine and uses ODBC to connect
to the databases.
もし、Unix に MyODBC
をインストールしたいなら、 ODBC
マネージャーも必要でしょう。 MyODBC
は Unix の ODBC マネージャー
でも動作することが知られています。
To install MyODBC
on Windows, you should download the
appropriate MyODBC
`.zip' file,
unpack it with WinZIP
or some similar program,
and execute the `SETUP.EXE' file.
Windows/NT の場合、MyODBC
をインストール時にいかのような
エラーになるかもしれません:
An error occurred while copying C:\WINDOWS\SYSTEM\MFC30.DLL. Restart Windows and try installing again (before running any applications which use ODBC)
The problem in this case is that some other program is using ODBC and
because of how Windows is designed, you may not in this case be able to
install a new ODBC drivers with Microsoft's ODBC setup program. In most
cases you can continue by just pressing Ignore
to copy the rest
of the MyODBC files and the final installation should still work.
これを解決するには、一度 ’セーフモード’でコンピュータを立ち上げ直し、
(windows リブート時に、F8キーを押すことで、セーフモードの選択が可能です)
MyODBC
をインストールして、リブートします:
MyODBC
をインストールしなくては
なりません。
GRANT
コマンドで可能です。
「4.3.1 GRANT
と REVOKE
構文」節参照.
MyODBC の設定画面には、MySQL 接続時のオプションがいくつか 設定できるようになっています。 もし問題がある場合は、これらを試します。
Windows95 上のサーバ名の記述には3つの可能性があります:
ip hostname例えば:
194.216.84.21 my_hostname
ODBC setup
を埋める方法の例:
Windows DSN name: test Description: This is my test database MySql Database: test Server: 194.216.84.21 User: monty Password: my_password Port:
Windows DSN name
項目の値は、あなたのwindows ODBC setup における
一意の名前です。
ODBC setup 画面で、Server
, User
, Password
, Port
フィールドを設定する必要はありません。
しかし、ここで設定をすると、後でサーバーに接続する際に、
設定した値がデフォルト値として使用されます。
使用時に値を変更するオプションはあります。
ポート番号が設定されていないなら、デフォルトポート (3306) が使用 されます。
もしオプションを Read options from C:\my.cnf
にすると,
client
と odbc
グループは `C:\my.cnf' ファイルから読まれます。
mysql_options()
で使用できる全てのオプションが利用可能です。
「8.4.3.163 mysql_options()
」節参照.
One can specify the following parameters for MyODBC
on
the [Servername]
section of an `ODBC.INI' file or
through the InConnectionString
argument in the
SQLDriverConnect()
call.
Parameter | Default value | Comment |
user | ODBC (on Windows) | The username used to connect to MySQL. |
server | localhost | The hostname of the MySQL server. |
database | The default database. | |
option | 0 | A integer by which you can specify how MyODBC should work. See below.
|
port | 3306 | The TCP/IP port to use if server is not localhost .
|
stmt | A statement that will be executed when connecting to MySQL .
| |
password | The password for the server user combination.
| |
socket | The socket or Windows pipe to connect to. |
The option argument is used to tell MyODBC
that the client isn't 100%
ODBC compliant. On Windows, one normally sets the option flag by
toggling the different options on the connection screen but one can also
set this in the opton argument. The following options are listed in the
same order as they appear in the MyODBC
connect screen:
Bit | Description |
1 | The client can't handle that MyODBC returns the real width of a column.
|
2 | The client can't handle that MySQL returns the true value of affected rows. If this flag is set then MySQL returns 'found rows' instead. One must have MySQL 3.21.14 or newer to get this to work. |
4 | Make a debug log in c:\myodbc.log. This is the same as putting MYSQL_DEBUG=d:t:O,c::\myodbc.log in `AUTOEXEC.BAT'
|
8 | Don't set any packet limit for results and parameters. |
16 | Don't prompt for questions even if driver would like to prompt |
32 | Simulate a ODBC 1.0 driver in some context. |
64 | Ignore use of database name in 'database.table.column'. |
128 | Force use of ODBC manager cursors (experimental). |
256 | Disable the use of extended fetch (experimental). |
512 | Pad CHAR fields to full column length. |
1024 | SQLDescribeCol() will return fully qualifed column names |
2048 | Use the compressed server/client protocol |
4096 | Tell server to ignore space after function name and before '(' (needed by PowerBuilder). This will make all function names keywords!
|
8192 | Connect with named pipes to a mysqld server running on NT.
|
16384 | Change LONGLONG columns to INT columns (some applications can't handle LONGLONG). |
32768 | Return 'user' as Table_qualifier and Table_owner from SQLTables (experimental) |
65536 | Read parameters from the client and odbc groups from `my.cnf'
|
131072 | Add some extra safety checks (should not bee needed but...) |
If you want to have many options, you should add the above flags! For example setting option to 12 (4+8) gives you debugging without package limits!
The default `MYODBC.DLL' is compiled for optimal performance. If
you want to debug MyODBC
(for example to enable tracing),
you should instead use `MYODBCD.DLL'. To install this file, copy
`MYODBCD.DLL' over the installed `MYODBC.DLL' file.
MyODBC
は以下でテストされました: Access, Admndemo.exe, C++-Builder,
Borland Builder 4, Centura Team Developer (formerly Gupta SQL/Windows),
ColdFusion (on Solaris and NT with svc pack 5), Crystal Reports,
DataJunction, Delphi, ERwin, Excel, iHTML, FileMaker Pro, FoxPro, Notes
4.5/4.6, SBSS, Perl DBD-ODBC, Paradox, Powerbuilder, Powerdesigner 32
bit, VC++, and Visual Basic.
If you know of any other applications that work with MyODBC
, please
send mail to myodbc@lists.mysql.com about this!
With some programs you may get an error like:
Another user has modifies the record that you have modified
. In most
cases this can be solved by doing one of the following things:
If the above doesn't help, you should do a MyODBC
trace file and
try to figure out why things go wrong.
Most programs should work with MyODBC
, but for each of those
listed here, we have tested it ourselves or received confirmation from
some user that it works:
Microsoft Data Access
Components
) from http://www.microsoft.com/data/. This will fix
the following bug in Access: when you export data to MySQL, the
table and column names aren't specified. Another way to around this bug
is to upgrade to MyODBC Version 2.50.33 and MySQL Version
3.23.x, which together provide a workaround for this bug!
You should also get and apply the Microsoft Jet 4.0 Service Pack 5 (SP5)
which can be found here
http://support.microsoft.com/support/kb/articles/Q 239/1/14.ASP.
This will fix some cases where columns are marked as #deleted#
in Access.
Note that if you are using MySQL Version 3.22, you must to apply the
MDAC patch and use MyODBC 2.50.32 or 2.50.34 and above to go around
this problem.
Return matching rows
. For Access 2.0, you should additionally enable
Simulate ODBC 1.0
.
TIMESTAMP(14)
or simple TIMESTAMP
is recommended instead of other TIMESTAMP(X)
variations.
#DELETED#
.
DOUBLE
float fields. Access fails when comparing with
single floats. The symptom usually is that new or updated rows may show
up as #DELETED#
or that you can't find or update rows.
tem
If you are linking a table through MyODBC, which has BIGINT
as
one of the column, then the results will be displayed as #DELETED
. The
work around solution is:
TIMESTAMP
as the data type, preferably
TIMESTAMP(14)
.
'Change BIGINT columns to INT'
in connection options dialog in
ODBC DSN Administrator
#DELETED#
, but newly
added/updated records will be displayed properly.
#Deleted#
or that you can't find or update rows.
Another user has changed your data
after
adding a TIMESTAMP
column, the following trick may help you:
Don't use table
data sheet view. Create instead a form with the
fields you want, and use that form
data sheet view. You should
set the DefaultValue
property for the TIMESTAMP
column to
NOW()
. It may be a good idea to hide the TIMESTAMP
column
from view so your users are not confused.
"Query|SQLSpecific|Pass-Through"
を選択すれば
直すことが可能です。
BLOB
フィールドを OLE OBJECTS
と認識します。
もし MEMO
フィールドを代わりに使用したいなら、 ALTER TABLE
を使って、
TEXT
型にフィールドを変更しなくてはなりません。
DATE
フィールドをいつも正しく扱うことが出来ません。
もしこれらの問題があった場合、フィールド型を DATETIME
に変えてください。
BYTE
, Access will try
to export this as TINYINT
instead of TINYINT UNSIGNED
.
This will give you problems if you have values > 127 in the column!
MyODBC
you need to put
attention in some default properties that aren't supported by the
MySQL server. For example, using the CursorLocation
Property
as adUseServer
will return for the RecordCount
Property
a result of -1. To have the right value, you need to set this
property to adUseClient
, like is showing in the VB code here:
Dim myconn As New ADODB.Connection Dim myrs As New Recordset Dim mySQL As String Dim myrows As Long myconn.Open "DSN=MyODBCsample" mySQL = "SELECT * from user" myrs.Source = mySQL Set myrs.ActiveConnection = myconn myrs.CursorLocation = adUseClient myrs.Open myrows = myrs.RecordCount myrs.Close myconn.CloseAnother workaround is to use a
SELECT COUNT(*)
statement
for a similar query to get the correct row count.
Return matching rows
.
Don't optimize column widths
and Return matching rows
.
Active
or use the
method Open
. Note that Active
will start by automatically
issuing a SELECT * FROM ...
query that may not be a good thing if
your tables are big!
MyODBC
for MySQL data
sources. Allaire has verified that MyODBC
Version 2.50.26
works with MySQL Version 3.22.27 and ColdFusion for Linux. (Any
newer version should also work.) You can download MyODBC
at
http://www.mysql.com/downloads/api-myodbc.html
ColdFusion Version 4.5.1 allows you to us the ColdFusion Administrator
to add the MySQL data source. However, the driver is not
included with ColdFusion Version 4.5.1. Before the MySQL driver
will appear in the ODBC datasources drop-down list, you must build and
copy the MyODBC
driver to
`/opt/coldfusion/lib/libmyodbc.so'.
The Contrib directory contains the program `mydsn-xxx.zip' which allows
you to build and remove the DSN registry file for the MyODBC driver
on Coldfusion applications.
VARCHAR
rather than ENUM
, as
it exports the latter in a manner that causes MySQL grief.
CONCAT()
関数を使用し、文字として SELECT してみて
ください。 例えば:
select CONCAT(rise_time), CONCAT(set_time) from sunrise_sunset;この方法で文字として返ってきた値を、Excel97 で時間として扱うようにすべきです。 この例の
CONCAT()
の目的は、フィールドの型が文字列であると ODBC をだます
ことです。
CONCAT()
がなければ、ODBC はフィールドの型が日付とわかるので、
Excel が今度はそれを理解できなくなります。
これは Excel のバグです。なぜなら文字を自動で日付に直すのですから。
これは単にテキストファイルの情報を扱う場合ならばいいのですが、
各項目の型を知らせる ODBC 接続の情報を扱う場合は、とても愚かな方法です。
MyODBC
driver and the Add-in Microsoft Query help.
For example, create a db with a table containing 2 columns of text:
mysql
client command-line tool.
MyODBC
(the BDE entry requires a BDE
Alias Editor that is free at a Delphi Super Page near
you. (Thanks to Bryan Brunton bryan@flesherfab.com for this):
fReg:= TRegistry.Create; fReg.OpenKey('\Software\ODBC\ODBC.INI\DocumentsFab', True); fReg.WriteString('Database', 'Documents'); fReg.WriteString('Description', ' '); fReg.WriteString('Driver', 'C:\WINNT\System32\myodbc.dll'); fReg.WriteString('Flag', '1'); fReg.WriteString('Password', ''); fReg.WriteString('Port', ' '); fReg.WriteString('Server', 'xmark'); fReg.WriteString('User', 'winuser'); fReg.OpenKey('\Software\ODBC\ODBC.INI\ODBC Data Sources', True); fReg.WriteString('DocumentsFab', 'MySQL'); fReg.CloseKey; fReg.Free; Memo1.Lines.Add('DATABASE NAME='); Memo1.Lines.Add('USER NAME='); Memo1.Lines.Add('ODBC DSN=DocumentsFab'); Memo1.Lines.Add('OPEN MODE=READ/WRITE'); Memo1.Lines.Add('BATCH COUNT=200'); Memo1.Lines.Add('LANGDRIVER='); Memo1.Lines.Add('MAX ROWS=-1'); Memo1.Lines.Add('SCHEMA CACHE DIR='); Memo1.Lines.Add('SCHEMA CACHE SIZE=8'); Memo1.Lines.Add('SCHEMA CACHE TIME=-1'); Memo1.Lines.Add('SQLPASSTHRU MODE=SHARED AUTOCOMMIT'); Memo1.Lines.Add('SQLQRYMODE='); Memo1.Lines.Add('ENABLE SCHEMA CACHE=FALSE'); Memo1.Lines.Add('ENABLE BCD=FALSE'); Memo1.Lines.Add('ROWSET SIZE=20'); Memo1.Lines.Add('BLOBS TO CACHE=64'); Memo1.Lines.Add('BLOB SIZE=32'); AliasEditor.Add('DocumentsFab','MySQL',Memo1.Lines);
Return matching rows
.
SHOW PROCESSLIST
will not work properly. The fix is to set
the option OPTION=16384
in the ODBC connect string or to set
the Change BIGINT columns to INT
option in the MyODBC connect screen.
You may also want to set the Return matching rows
option.
[Microsoft][ODBC Driver Manager] Driver does
not support this parameter
the reason may be that you have a
BIGINT
in your result. Try setting the Change BIGINT
columns to INT
option in the MyODBC connect screen.
Don't optimize column widths
.
AUTO_INCREMENT
フィールドの値を ODBC で得る方法
共通の問題は、INSERT
で自動的に生成されるIDの値を得ることです。
ODBCでは、以下のようにします( 例中の auto
が AUTO_INCREMENT
フィー
ルドです):
INSERT INTO foo (auto,text) VALUES(NULL,'text'); SELECT LAST_INSERT_ID();
もしくは、他のテーブルにIDを挿入するだけなら以下のようにします:
INSERT INTO foo (auto,text) VALUES(NULL,'text'); INSERT INTO foo2 (id,text) VALUES(LAST_INSERT_ID(),'text');
「8.4.6.3 最後に挿入された行のユニーク ID をどのように得られるか?」節参照.
For the benefit of some ODBC applications (at least Delphi and Access), the following query can be used to find a newly inserted row:
SELECT * FROM tbl_name WHERE auto IS NULL;
もし MyODBC
使用時に難しい問題にあたった場合、
ODBC マネージャのログファイル (ODBCADMIN からリクエストしたときのログ)
と MyODBC
のログを取り始めるべきです。
これはいかなる問題にも解決の糸口になるはずです。
MyODBC
のログを取るには、以下のように行ないます:
MyODBC
connect/configure
screen. The log will be written to file `C:\myodbc.log'.
If the trace option is not remembered when you are going back to the
above screen, it means that you are not using the myodbcd.dll
driver (see the item above).
Check the MyODBC trace file
, to find out what could be wrong.
You should be able to find out the issued queries by searching after
the string >mysql_real_query
in the `myodbc.log' file.
You should also try duplicating the queries in the mysql
monitor
or admndemo
to find out if the error is MyODBC or MySQL.
If you find out something is wrong, please only send the relevant rows (max 40 rows) to myodbc@lists.mysql.com. Please never send the whole MyODBC or ODBC log file!
If you are unable to find out what's wrong, the last option is to make an archive (tar or zip) that contains a MyODBC trace file, the ODBC log file, and a README file that explains the problem. You can send this to ftp://support.mysql.com/pub/mysql/secret/. Only we at MySQL AB will have access to the files you upload, and we will be very discrete with the data!
If you can create a program that also shows this problem, please upload this too!
If the program works with some other SQL server, you should make an ODBC log file where you do exactly the same thing in the other SQL server.
Remember that the more information you can supply to us, the more likely it is that we can fix the problem!
C API コードは MySQL とともに配布されます。これは
libmysqlclient
ライブラリに含まれ、C プログラムからデータベースへ
のアクセスを許します。
MySQL ソースディストリビューション内のクライアントの多くは C で書かれています。C API の使 用法を示す例を探すなら、これらのクライアントを調べてください。
他のクライアント API の多く(Java を除く全て)は、MySQL サーバと の通信にこのライブラリを使用します。そのため、例えば、他のクライアントプ ログラムで使用されるのと同じ環境変数の多くの利点を得ることができます。そ れらはライブラリから参照されるからです。これらの変数のリストについては 「4.8 MySQL Client-Side Scripts and Utilities」節 を参照して下さい。
クライアントは最大通信バッファサイズを持ちます。最初に割り当てられるバッ ファのサイズ(16K バイト)は自動的に最大サイズ(デフォルトは 16M)まで増加し ます。バッファサイズは必要に応じて増加するため、単純にデフォルトの最大制 限を増加しても、さらに内部で資源を使用することはありません。このサイズチェッ クは主に間違ったクエリと通信パケットのためのチェックです。
通信バッファは一つの SQL ステートメント(クライアントからサーバへの通信)と、
返されるデータ(サーバからクライアントへの通信)の1レコードを含むのに
十分大きくなくてはいけません。各スレッドの
通信バッファは、任意のレコードやクエリを処理するために、指定された制限まで動的
に増大します。例えば、最大 16M のデータを含む BLOB
値がある場合、
少なくとも 16M を通信バッファ制限として持つ必要があります(サーバとクライ
アントの両方で)。
クライアントのデフォルトの最大値は 16M ですが、サーバの最大値のデフォルトは
1M です。これはサーバ起動時に、max_allowed_packet
パラメータの
値を変更することにより、増やすことが出来ます。
「5.5.2 サーバーパラメーターのチューニング」節参照.
MySQL サーバは、各クエリ後に各通信バッファを
net_buffer_length
バイトに縮小します。
クライアントでは、接続に割り当てられたバッファのサイズは、接続が閉じられるまで減少しません。
クライアントメモリは接続がクローズされた時に調整されます。
スレッドプログラミングについては、 「8.4.8 スレッドクライアントを作る方法」節参照. を参考にしてください。
MYSQL
MYSQL_RES
SELECT
, SHOW
, DESCRIBE
, EXPLAIN
)の結果を表わ
します。クエリから返される情報は、この節の残りでは結果セットと呼
ばれます。
MYSQL_ROW
mysql_fetch_row()
の呼び出しによりレコードが獲得
されます。
MYSQL_FIELD
mysql_fetch_field()
を繰り返し呼び出すことにより、各フィールドの
MYSQL_FIELD
構造体を得ることができます。
フィールド値はこの構造体の一部ではありません; それは MYSQL_ROW
構造
体に含まれています。
MYSQL_FIELD_OFFSET
mysql_field_seek()
で使用されます。)オフセットはレコード内のフィールド
番号で、0 から始まります。
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
値は次の一つです:
型の値 | 型の意味 |
FIELD_TYPE_TINY | TINYINT フィールド
|
FIELD_TYPE_SHORT | SMALLINT フィールド
|
FIELD_TYPE_LONG | INTEGER フィールド
|
FIELD_TYPE_INT24 | MEDIUMINT フィールド
|
FIELD_TYPE_LONGLONG | BIGINT フィールド
|
FIELD_TYPE_DECIMAL | DECIMAL または NUMERIC フィールド
|
FIELD_TYPE_FLOAT | FLOAT フィールド
|
FIELD_TYPE_DOUBLE | DOUBLE または 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 | BLOB または TEXT フィールド (最大長を確定するには max_length を使用して下さい)
|
FIELD_TYPE_SET | SET フィールド
|
FIELD_TYPE_ENUM | ENUM フィールド
|
FIELD_TYPE_NULL | NULL 型 フィールド
|
FIELD_TYPE_CHAR | 非推奨; FIELD_TYPE_TINY を代わりに使用してください
|
IS_NUM()
マクロで、フィールドが数値タイプかどうかをテストできます。
フィールドが数値の場合、type
メンバを IS_NUM()
に渡すと
TRUE と評価します:
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()
を使用する場合は、この変数の値は 0 になります。
unsigned int flags
flags
値は 0 または次のビットの一つ
以上の組み合わせです:
フラグの値 | フラグの意味 |
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 である (非推奨)
|
SET_FLAG | Field is a SET (deprecated)
|
BLOB_FLAG | フィールドは BLOB または TEXT である (非推奨)
|
TIMESTAMP_FLAG | フィールドは TIMESTAMP である (非推奨)
|
BLOB_FLAG
, ENUM_FLAG
, SET_FLAG
, TIMESTAMP_FLAG
の使用は推奨さ
れません。これらは型の属性ではなくフィールドの型を示すからです。代わり
に field->type
を FIELD_TYPE_BLOB
, FIELD_TYPE_ENUM
,
FIELD_TYPE_SET
, 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 ならば真 (非推奨; 代わりに field->type をテストして下さい)
|
unsigned int decimals
C API には次に一覧された関数が存在します。これらの関数は次の節でかな り詳細に説明されています。 「8.4.3 C API 関数説明」節参照。
Function | Description |
mysql_affected_rows() |
最後の UPDATE , DELETE , INSERT クエリによって変更/削
除/挿入されたレコード数を返します。
|
mysql_change_user() | 接続中ののユーザとデータベースを変更します。 |
mysql_character_set_name() | 接続のデフォルト文字セットの名前を返します。 |
mysql_close() | サーバ接続をクローズします。 |
mysql_connect() |
MySQL サーバに接続します。この関数は推奨されません; 代わりに
mysql_real_connect() を使用してください。
|
mysql_create_db() |
データベースを生成します。この関数は推奨されません; 代わりに SQL コマン
ド CREATE DATABASE を使用してください。
|
mysql_data_seek() | クエリ結果セット中の任意のレコードにシークします。 |
mysql_debug() |
与えられた文字列で DBUG_PUSH を行ないます。
|
mysql_drop_db() |
データベースを破棄します。この関数は推奨されません; 代わりに SQL コマン
ド DROP DATABASE を使用してください。
|
mysql_dump_debug_info() | サーバに、デバッグ情報をログに書き出させます。 |
mysql_eof() |
結果セットの最後のレコードが読まれたかどうかを判定します。この関数は推奨されませ
ん; 代わりに mysql_errno() または mysql_error() を使用して下
さい。
|
mysql_errno() | 最後の MySQL 関数からのエラー番号を返します。 |
mysql_error() | 最後の MySQL 関数からのエラーメッセージを返します。 |
mysql_escape_string() | SQL ステートメント内で使用するために文字列中の特殊文字をエスケープします。 |
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_fetch_field() で使用されたフィールドカーソルの位置を返
します。
|
mysql_free_result() | 結果セットによって使用されたメモリを解放します。 |
mysql_get_client_info() | クライアントバージョン情報を返します。 |
mysql_get_host_info() | 接続を説明する文字列を返します。 |
mysql_get_server_version() | Returns version number of server as an integer (new in 4.1). |
mysql_get_proto_info() | 接続に使用されるプロトコルバージョンを返します。 |
mysql_get_server_info() | サーバのバージョン番号を返します。 |
mysql_info() | 最後に実行されたクエリについての情報を返します。 |
mysql_init() |
MYSQL 構造体を獲得または初期化します。
|
mysql_insert_id() |
AUTO_INCREMENT フィールドに最後に生成された ID を返します。
|
mysql_kill() | 指定されたスレッドを殺します。 |
mysql_list_dbs() | 簡易正規表現に適合するデータベース名を返します。 |
mysql_list_fields() | 簡易正規表現に適合するフィールド名を返します。 |
mysql_list_processes() | 現在のサーバスレッドのリストを返します。 |
mysql_list_tables() | 簡易正規表現に適合するテーブル名を返します。 |
mysql_num_fields() | 結果セット中のフィールド数を返します。 |
mysql_num_rows() | 結果セット中のレコード数を返します。 |
mysql_options() |
mysql_connect() のための接続オプションを設定します。
|
mysql_ping() | サーバへの接続が動作しているかどうかをチェックします。 必要であれば再接続します。 |
mysql_query() | NULL 終端文字列として記述された SQL クエリを実行します。 |
mysql_real_connect() | MySQL サーバに接続します。 |
mysql_real_escape_string() | Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection. |
mysql_real_query() | 数えられた文字列として記述された SQL クエリを実行します。 |
mysql_reload() | 権限テーブルを再読み込みするようにサーバに指示します。 |
mysql_row_seek() |
結果セット内のあるレコードへシークします。mysql_row_tell() から返される値を
使用します。
|
mysql_row_tell() | レコードカーソルの位置を返します。 |
mysql_select_db() | データベースを選択します。 |
mysql_shutdown() | データベースサーバをシャットダウンします。 |
mysql_stat() | 文字列でサーバ状態を返します。 |
mysql_store_result() | クライアントに完全な結果セットを取り出します。 |
mysql_thread_id() | 現在のスレッド ID を返します。 |
mysql_thread_save() | Returns 1 if the clients are compiled as thread-safe. |
mysql_use_result() | 各レコードの動的結果セットを初期化します。 |
サーバへ接続するには、接続ハンドラを初期化するために mysql_init()
を呼びだし、それから mysql_real_connect()
をそのハンドラで呼びだし
ます (ホスト名、ユーザ名、パスワードのような他の情報に加えて)。
Upon connection, mysql_real_connect()
sets the
reconnect
flag (part of the MYSQL structure) to a value of
1
. This flag indicates, in the event that a query cannot be
performed because of a lost connection, to try reconnecting to the
server before giving up.
その接続で
の処理が終了した時は、接続を終了させるために mysql_close()
を呼びだ
します。
接続が有効な間は、クライアントは mysql_query()
または
mysql_real_query()
を使用して SQL クエリをサーバに送信できます。こ
の2つの違いは、mysql_query()
は NULL終端文字列としてクエリが記述さ
れることを期待するのに対し、mysql_real_query()
は数えられた文字列を
期待することです。文字列がバイナリデータ(NULバイトを含みことがある)を含む
場合は、mysql_real_query()
を使用する必要があります。
非SELECT
クエリ(例えば、INSERT
, UPDATE
,
DELETE
)では、どれくらいのレコードが変更(影響)されたかを
mysql_affected_rows()
を呼び出すことで見つけ出すことができます。
SELECT
クエリでは、選択されたレコードを結果セットとして取り出します。
(注意: いくつかのステートメントは、レコードを返すという点で
SELECT
に似ています。それは SHOW
, DESCRIBE
,
EXPLAIN
です。これらは SELECT
ステートメントと同じ方法で扱わ
れるべきです。)
クライアントが結果セットを処理するには2つの方法があります。一つ目は、
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()
を呼び出し、そ
れが使用していたメモリを解放して下さい。
この2つの取り出し機構は相補的なものです。クライアントプログラムは、必要に
よってもっとも適切なアプローチを選択すべきです。慣例的に、クライアントは一
般に mysql_store_result()
を使用する傾向にあります。
mysql_store_result()
の利点は、すべてのレコードをクライアントに取っ
て来るため、連続してレコードをアクセスできるだけでなく、結果セット中の現在
のレコード位置を変更するために、mysql_data_seek()
や
mysql_row_seek()
を使用して、結果セットの中を後や前に移動することが
できます。また、mysql_num_rows()
を呼び出すことで、レコード数を見つ
けることもできます。一方、mysql_store_result()
の必要メモリは、大き
な結果セットではとても高く、out-of-memory 状態に遭遇する可能性が高くなりま
す。
mysql_use_result()
の利点は、一度に一つのレコードだけを保持するため、
クライアントが結果セットに要求するメモリが少ないことです(そして、割当のオー
バーヘッドも少ないので、mysql_use_result()
はより速くなります)。不
利な点は、サーバの拘束を避けるため、各レコードを素早く処理する必要があるこ
と、結果セット中でレコードのランダムアクセスができないこと(レコードを順番
にアクセスすることしかできません)、そして、すべてのレコードを取り出さない
限り、結果セット中にいくつのレコードがあるかを知ることができないことです。
さらに、あなたが探している情報を、検索の途中で見つけることができて、問題が
解決したとしても、すべてのレコードを取り出さなければなりません。
API はクライアントがクエリが SELECT
であるかどうかを知ることなしに、
(必要時だけレコードを取り出す)クエリに適切に応答できるようにします。
それぞれの mysql_query()
(または mysql_real_query()
)の後で、
mysql_store_result()
を呼び出すことで、これが可能です。結果セットの
呼び出しが成功すると、クエリは SELECT
であり、レコードを読むことが
できます。結果セット呼び出しが失敗した場合は、結果が実際に期待されたもので
あるかどうかを確定するために、mysql_field_count()
を呼び出してくだ
さい。mysql_field_count()
が 0 を返す場合は、クエリはデータを返しま
せん(クエリが INSERT
, UPDATE
, DELETE
等であることを
示します)。つまりレコードが返ることを期待できません。
mysql_field_count()
が 0 でない場合は、クエリはレコードを返すべきな
のに、返さなかったということです。これはクエリが SELECT
で失敗した
ということを示します。これをどのように行なうことができるかの例は、
mysql_field_count()
の説明を参照してください。
mysql_store_result()
と mysql_use_result()
はどちらも、結果
セットを作るフィールドについての情報(フィールドの数、その名前や型など)を
獲得することができます。mysql_fetch_field()
を繰り返し呼び出すこと
で順番に、または、mysql_fetch_field_direct()
を呼び出すことでレコー
ド内のフィールド番号で、レコード内のフィールド情報にアクセスすることができ
ます。現在のフィールドカーソル位置は mysql_field_seek()
を呼び出す
ことで変更できます。フィールドカーソルの設定は、その後の
mysql_fetch_field()
呼び出しに影響します。
mysql_fetch_fields()
を呼び出すことで、一度にすべてのフィールドの情
報を得ることもできます。
エラーの検出、報告については、mysql_errno()
と
mysql_error()
関数の方法によって、MySQL はエラー情報へのア
クセスを提供します。これらは、最後に呼び出された成功または失敗し得る関数に
ついてのエラーコードとエラーメッセージを返し、エラーがいつ何で発生したかを
確定することができます。
以下の説明では、NULL
の引数または戻り値は C プログラミング言語で
の NULL
を意味します。MySQL NULL
値ではありません。
関数は通常ポインタか整数の値を返します。しかし関数説明に記述がある場合、
ポインタを返す関数は、成功を示すために非 NULL
値を返し、エラーを示すた
めに NULL
を返します。整数を返す関数は、成功を示すために 0 を返し、
エラーを示すために非0を返します。``非0'' は関数説明が他に述べていない限
り、その意味になることに注意してください; 関数説明が他に述べている場合、
これらに対して 0 以外の固有の値をテストしないでください:
if (result) /* 正しい */ ... error ... if (result < 0) /* 間違い */ ... error ... if (result == -1) /* 間違い */ ... error ...
関数がエラーを返すとき、関数説明の エラー 節が起り得るエラーの
種類を一覧しています。mysql_errno()
の呼び出しによってどれが発生
したかを見つけ出すことができます。エラーを表現する文字列は
mysql_error()
の呼び出しによって得られます。
mysql_affected_rows()
my_ulonglong mysql_affected_rows(MYSQL *mysql)
最後の UPDATE
によって変更されたレコード数、または、DELETE
によって削除されたレコード数、INSERT
によって挿入されたレコード数を
返します。UPDATE
, DELETE
, INSERT
ステートメントでの
mysql_query()
直後に呼び出します。SELECT
ステートメントでは、
mysql_affected_rows()
は mysql_num_rows()
に似た動きをします。
0 より大きい整数は影響された行数または取り出された行数を示します。0 は
UPDATE
ステートメントで更新されたレコードがないこと、またはクエリの
WHERE
節に適合したレコードがないこと、またはまだなんのクエリも実行
していないことを示します。-1 はクエリがエラーを返したこと、あるいは
SELECT
クエリで、mysql_affected_rows()
が
mysql_store_result()
呼び出しよりも先に呼び出されたことを揣摩します。
無し。
mysql_query(&mysql,"UPDATE products SET cost=cost*1.25 WHERE group=10"); printf("%ld products updated",(long) mysql_affected_rows(&mysql));
If one specifies the flag CLIENT_FOUND_ROWS
when connecting to
mysqld
, mysql_affected_rows()
will return the number of
rows matched by the WHERE
statement for UPDATE
statements.
Note that when one uses a REPLACE
command,
mysql_affected_rows()
will return 2 if the new row replaced and
old row. This is because in this case one row was inserted after the
duplicate was deleted.
mysql_change_user()
my_bool mysql_change_user(MYSQL *mysql, const char *user, const
char *password, const char *db)
ユーザを変更し、mysql
で示された接続上で、db
で示されたデー
タベースがデフォルト(現在の)データベースになります。その後のクエリでは、
明示的なデータベースの指定を含んでいないテーブル参照について、このデータベー
スがデフォルトになります。
この関数は MySQL 3.23.3 で導入されました。
mysql_change_user()
は接続されたユーザが認証されない場合、またはデー
タベースを使用する権限を持っていない場合に失敗します。この場合、ユーザとデー
タベースは変更されません。
デフォルトデータベースを持ちたくない場合、db
パラメータを
NULL
に設定できます。
成功時 0。エラーが発生した場合は非0。
mysql_real_connect()
から得られるものと同じです。
CR_COMMANDS_OUT_OF_SYNC
CR_SERVER_GONE_ERROR
CR_SERVER_LOST
CR_UNKNOWN_ERROR
ER_UNKNOWN_COM_ERROR
ER_ACCESS_DENIED_ERROR
ER_BAD_DB_ERROR
ER_DBACCESS_DENIED_ERROR
ER_WRONG_DB_NAME
if (mysql_change_user(&mysql, "user", "password", "new_database")) { fprintf(stderr, "Failed to change user. Error: %s\n", mysql_error(&mysql)); }
mysql_character_set_name()
const char *mysql_character_set_name(MYSQL *mysql)
Returns the default character set for the current connection.
Starting from MySQL 4.0.6 this command will always ROLLBACK
any
active transactions, close all temporary tables, unlock all locked
tables and reset the state as if one had done a new connect.
This will happen even if the user didn't change.
The default character set
None.
mysql_close()
void mysql_close(MYSQL *mysql)
前にオープンされた接続をクローズします。ハンドルが mysql_init()
ま
たは mysql_connect()
で自動的に割り当てられた場合、
mysql_close()
は mysql
で示される接続ハンドルの解放も行ない
ます。
無し。
無し。
mysql_connect()
MYSQL *mysql_connect(MYSQL *mysql, const char *host, const char *user, const char *passwd)
この関数は推奨されません。代わりに mysql_real_connect()
の使用を
お勧めします。
mysql_connect()
は host
上で動作している MySQL デー
タベースエンジンへの接続の確立を試みます。mysql_get_client_info()
を除く他のすべての API 関数を実行する前にmysql_connect()
が成功終了
している必要があります。
パラメータの意味は mysql_real_connect()
の対応するパラメータと同じですが、
接続パラメータは NULL
にできることが異なります。この場合 C API は接
続構造体に自動的にメモリを割り当て、mysql_close()
呼び出し時にそれ
を解放します。このアプローチの不利な点は接続が失敗した場合にエラーメッセー
ジを取り出すことができないことです。(mysql_errno()
または
mysql_error()
からエラー情報を得るには、正しい MYSQL
ポイン
タを提供する必要があります。)
mysql_real_connect()
と同じ
mysql_real_connect()
と同じ
mysql_create_db()
int mysql_create_db(MYSQL *mysql, const char *db)
db
引数によって指定されたデータベースを作成します。
この関数は推奨されません。代わりに mysql_query()
を使って、SQL
CREATE DATABASE
ステートメントを発行することをお勧めします。
データベースの作成が成功した場合は0。エラーが発生した場合は非0。
CR_COMMANDS_OUT_OF_SYNC
CR_SERVER_GONE_ERROR
CR_SERVER_LOST
CR_UNKNOWN_ERROR
if(mysql_create_db(&mysql, "my_database")) { fprintf(stderr, "Failed to create new database. Error: %s\n", mysql_error(&mysql)); }
mysql_data_seek()
void mysql_data_seek(MYSQL_RES *result, my_ulonglong offset)
クエリ結果セット中の任意のレコードにシークします。これは、結果セット構造体
がクエリのすべての結果を持っていることを要求します。そのため、
mysql_data_seek()
は mysql_store_result()
と共にだけ使用され、
mysql_use_result()
と共には使用できません。
オフセットの値は 0
から mysql_num_rows(result)-1
でなくては
なりません。
無し。
無し。
mysql_debug()
void mysql_debug(const char *debug)
与えられた文字列で DBUG_PUSH
を行ないます。mysql_debug()
は Fred Fish が作成した debug library を使用します。この関数を使用するためには、デバッ
グをサポートするように、クライアントライブラリをコンパイルする必要があり
ます。
「E.1 MySQL server のデバッグ」節参照. 「E.2 Debugging a MySQL client」節参照.
無し。
無し。
次に示した呼び出しは、クライアントライブラリが、クライアントマシン上の `/tmp/client.trace' にトレースファイルを生成します:
mysql_debug("d:t:O,/tmp/client.trace");
mysql_drop_db()
int mysql_drop_db(MYSQL *mysql, const char *db)
db
引数によって指定されたデータベースを破棄します。
この関数は推奨されません。代わりに mysql_query()
を使って、SQL
DROP DATABASE
ステートメントを発行することをお勧めします。
データベースの破棄が成功した場合は0。エラーが発生した場合は非0。
CR_COMMANDS_OUT_OF_SYNC
CR_SERVER_GONE_ERROR
CR_SERVER_LOST
CR_UNKNOWN_ERROR
if(mysql_drop_db(&mysql, "my_database")) fprintf(stderr, "Failed to drop the database: Error: %s\n", mysql_error(&mysql));
mysql_dump_debug_info()
int mysql_dump_debug_info(MYSQL *mysql)
いくつかのデバッグ情報をログにダンプするようにサーバに指示します。この動
作をするためには、接続されたユーザが SUPER
権限
(version4.0.2以上。未満はPROCESS
権)を持っていなけ
ればなりません。
コマンドが成功した場合は0。コマンドが失敗した場合は非0。
CR_COMMANDS_OUT_OF_SYNC
CR_SERVER_GONE_ERROR
CR_SERVER_LOST
CR_UNKNOWN_ERROR
mysql_eof()
my_bool mysql_eof(MYSQL_RES *result)
この関数は推奨されません。mysql_errno()
か mysql_error()
が
代わりに使用できます。
mysql_eof()
は結果セットの最後のレコードが読まれたかどうかを調べま
す。
mysql_store_result()
の呼び出しが成功して、結果セットを入手した場合、
クライアントは一つのオペレーションですべてのセットを受け取ります。この場合、
mysql_fetch_row()
から返される NULL
は、常に結果セットの終端
に達したことを意味し、mysql_eof()
を呼ぶ必要はありません。
hen used
with mysql_store_result()
, mysql_eof()
will always return
true.
一方、結果セット取り出しの初期化のために mysql_use_result()
を使用
する場合、セットのレコードは mysql_fetch_row()
を繰り返し呼ぶことに
より、ひとつずつサーバから獲得されます。この処理中に接続上でエラーが発生し
得るため、mysql_fetch_row()
からの戻り値 NULL
は、通常必ずし
も結果セットの終端に達したことを意味しません。この場合
mysql_eof()
を使用して、何が起こったかを検出できます。結果セットの
終端に達した場合は mysql_eof()
は非0値を返し、エラーが発生した場合
は 0 を返します。
歴史的に mysql_eof()
は標準 MySQL エラー関数
mysql_errno()
と mysql_error()
以前に遡ります。これらのエラー
関数は同じ情報を提供するので、これらの使用が mysql_eof()
よりも好ま
れます。mysql_eof()
は現在推奨されません。(実際、これらは多くの情
報を提供します。エラー関数はエラーが発生した時のエラーの理由を示しますが、
mysql_eof()
は真偽値だけを返します。)
エラーが発生しなかった場合は0。結果セットの終端に達した場合は非0。
無し。
次の例は mysql_eof
の使用方法を示します:
mysql_query(&mysql,"SELECT * FROM some_table"); result = mysql_use_result(&mysql); while((row = mysql_fetch_row(result))) { // do something with data } if(!mysql_eof(result)) // mysql_fetch_row() failed due to an error { fprintf(stderr, "Error: %s\n", mysql_error(&mysql)); }
しかし、標準 MySQL エラー関数で同じ効果を得ることができます:
mysql_query(&mysql,"SELECT * FROM some_table"); result = mysql_use_result(&mysql); while((row = mysql_fetch_row(result))) { // do something with data } if(mysql_errno(&mysql)) // mysql_fetch_row() failed due to an error { fprintf(stderr, "Error: %s\n", mysql_error(&mysql)); }
mysql_errno()
unsigned int mysql_errno(MYSQL *mysql)
mysql
によって指定された接続上で、最後に呼び出された API 関数の成否のエラーコー
ドを返します。戻り値0はエラーが発生しなかったことを意味します。クライア
ントエラーメッセージ番号は `errmsg.h' にリストされています。サーバ
エラーメッセージ番号は `mysqld_error.h' にリストされています。
In the
MySQL source distribution you can find a complete list of
error messages and error numbers in the file `Docs/mysqld_error.txt'.
エラーコード値。エラーが発生していない場合は0。
無し。
mysql_error()
char *mysql_error(MYSQL *mysql)
mysql
によって指定された接続上で、 mysql_error()
は
最後に呼び出された API 関数の成否を、エラーメッセージとして返します。
エラー発生しなかった場合は空文字列 (""
) が返されます。
これは次の2つのテストが同じであることを意味します:
if(mysql_errno(&mysql)) { // an error occurred } if(mysql_error(&mysql)[0] != '\0') { // an error occurred }
クライアントエラーメッセージの言語は MySQL クラ イアントライブラリの再コンパイルで変更できます。現在はいくつかの言語で書かれた クライアントエラーメッセージを選択できます。 「4.6.2 Non-English Error Messages」節参照.
エラーを表わす文字列。 エラーが発生していない場合は空文字列。
無し。
mysql_escape_string()
You should use mysql_real_escape_string()
instead!
This function is identical to mysql_real_escape_string()
except
that mysql_real_escape_string()
takes a connection handler as
its first argument and escapes the string according to the current
character set. mysql_escape_string()
does not take a connection
argument and does not respect the current charset setting.
mysql_fetch_field()
MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *result)
結果セットの一つのフィールドの定義を MYSQL_FIELD
構造体として返しま
す。結果セット内の全てのフィールドについて情報を取り出すには、この関数を繰
り返し呼んでください。mysql_fetch_field()
はフィールドが残っていな
いと NULL
を返します。
mysql_fetch_field()
は、新しい SELECT
クエリを実行するたびに、
最初のフィールドについての情報を返すようにリセットされます。
mysql_fetch_field()
で返されるフィールドは
mysql_field_seek()
の呼び出しにも影響をうけます。
テーブルを SELECT
するために mysql_query()
を呼び、しかしま
だ mysql_store_result()
を呼んでいない場合、
mysql_fetch_field()
を BLOB
フィールドの長さの問い合わせに使
用すると、MySQL はデフォルトの blob 長 (8K bytes) を返します。
(8K サイズになるのは、MySQL は BLOB
の最大長を知らないから
です。これはいつかコンフィグ可能になるべきです。) 一度結果セットを取り出せ
ば、field->max_length
は指定したクエリ内でのこのフィールドの最大値
の長さを含みます。
現在のフィールドの MYSQL_FIELD
構造体。フィールドが残っていない場合は
NULL
。
無し。
MYSQL_FIELD *field; while((field = mysql_fetch_field(result))) { printf("field name %s\n", field->name); }
mysql_fetch_fields()
MYSQL_FIELD *mysql_fetch_fields(MYSQL_RES *result)
結果セットのすべての MYSQL_FIELD
構造体の配列を返します。各構造体は
結果セットの一つのフィールドのフィールド定義を提供します。
結果セットの全ての項目の MYSQL_FIELD
構造体の配列。
無し。
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); }
mysql_fetch_field_direct()
MYSQL_FIELD *mysql_fetch_field_direct(MYSQL_RES *result, unsigned int fieldnr)
結果セット中のフィールドを示すフィールド番号 fieldnr
が与えられ、そ
のフィールドのフィールド定義を MYSQL_FIELD
構造体として返します。こ
の関数は任意のフィールドについての定義を取り出すことに使用できます。
fieldnr
の値は 0 から mysql_num_fields(result)-1
の範囲にす
べきです。
指定されたフィールドの MYSQL_FIELD
構造体。
無し。
unsigned int num_fields; unsigned int i; MYSQL_FIELD *field; num_fields = mysql_num_fields(result); for(i = 0; i < num_fields; i++) { field = mysql_fetch_field_direct(result, i); printf("Field %u is %s\n", i, field->name); }
mysql_fetch_lengths()
unsigned long *mysql_fetch_lengths(MYSQL_RES *result)
結果セット中の現在のレコードのフィールドの長さを返します。フィールドの値をコピーする場合、
この長さ情報は最適化にも有用です。strlen()
の呼び出しを回避できる
ためです。
さらに、結果セットがバイナリデータを持つ場合は、データのサイズを特定するためにこの関数を使わなければなりません。
なぜなら strlen()
は NULL 文字を含むフィールドについての結果を正しく返さないからです。
空フィールドの長さと NULL
値を含むフィールドの長さは 0 です。この2
つのケースを区別する方法については、mysql_fetch_row()
の説明を参照
して下さい。
各フィールドのサイズ (終端 NUL 文字は含みません)を提供する unsigned long
整数の配列。
エラーが発生した場合は NULL
。
mysql_fetch_lengths()
は結果セットの現在のレコードについてだけ有効
です。mysql_fetch_row()
を呼び出す前、または結果の全てのレコードを
取り出した後にこれを呼んだ場合、NULL
が返されます。
MYSQL_ROW row; unsigned long *lengths; unsigned int num_fields; unsigned int i; row = mysql_fetch_row(result); if (row) { num_fields = mysql_num_fields(result); lengths = mysql_fetch_lengths(result); for(i = 0; i < num_fields; i++) { printf("Column %u is %lu bytes in length.\n", i, lengths[i]); } }
mysql_fetch_row()
MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)
結果セットの次のレコードを取り出します。mysql_store_result()
の後に使用すると、
これ以上取り出すレコードがない時は、NULL
を返します。
mysql_use_result()
の後に使用するなら、
これ以上取り出すレコードがない場合やエラーが発生した場合に 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
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"); }
mysql_field_count()
unsigned int mysql_field_count(MYSQL *mysql)
3.22.24 より前の MySQL
バージョンを使用している場合、
unsigned int mysql_num_fields(MYSQL *mysql)
を代わりに使用すべきで
す。
接続上の最後のクエリのフィールド数を返します。
この関数は通常 mysql_store_result()
が NULL
を返した時(そし
てこのように結果セットポインタを持っていない時)に使用されます。この場合、
mysql_store_result()
が空でない結果を提供すべきかどうかを調べるため
に、mysql_field_count()
を呼び出すことができます。これは、クエリが
SELECT
(または SELECT
に似た)ステートメントであるかを知るこ
と無しに、クライアントプログラムに、適切な行動をとらせることができます。下
に示される例は、これをどのように行なうことができるかを説明しています。
「8.4.6.1 mysql_query()
が成功を返した後、mysql_store_result()
が NULL
を返す時があるのは何故?」節参照.
結果セット中のフィールド番号を表す unsigned integer。
無し。
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)
に置き換えることです。この場合、ステートメント
が SELECT
かどうかを mysql_field_count()
の値から推測するの
ではなく、直接 mysql_store_result()
からのエラーをチェックします。
mysql_field_seek()
MYSQL_FIELD_OFFSET mysql_field_seek(MYSQL_RES *result, MYSQL_FIELD_OFFSET offset)
与えられたオフセットにフィールドカーソルを設定します。次の
mysql_fetch_field()
の呼び出しはそのオフセットに対応したフィールドを取
り出します。
レコードの最初にシークするには、0 の offset
値を渡してください。
フィールドカーソルの前の値。
無し。
mysql_field_tell()
MYSQL_FIELD_OFFSET mysql_field_tell(MYSQL_RES *result)
最後の mysql_fetch_field()
に使用したフィールドカーソルの位置を返
します。この値は mysql_field_seek()
への引数として使用できます。
フィールドカーソルの現在のオフセット。
無し。
mysql_free_result()
void mysql_free_result(MYSQL_RES *result)
mysql_store_result()
, mysql_use_result()
,
mysql_list_dbs()
等によって結果セットに割り当てられたメモリを解放
します。結果セットで何かを行なった時、mysql_free_result()
を呼び
出してそれが使用したメモリを解放する必要があります。
無し。
無し。
mysql_get_client_info()
char *mysql_get_client_info(void)
クライアントライブラリバージョンを表わす文字列を返します。
MySQL クライアントライブラリバージョンを表わす文字列。
無し。
mysql_get_server_version()
unsigned long mysql_get_server_version(MYSQL *mysql)
Returns version number of server as an integer (new in 4.1).
A number that represents the MySQL server version in format:
main_version*10000 + minor_version *100 + sub_version
For example, 4.1.0 is returned as 40100.
This is useful to quickly determine the version of the server in a client program to know if some capability exits.
None.
mysql_get_host_info()
char *mysql_get_host_info(MYSQL *mysql)
使用中の接続タイプを表わす文字列を返します。サーバのホスト名を含みます。
サーバホスト名と接続タイプを表わす文字列。
無し。
mysql_get_proto_info()
unsigned int mysql_get_proto_info(MYSQL *mysql)
現在の接続に使用されているプロトコルバージョンを返します。
現在の接続に使用されているプロトコルバージョンを表わす符号無し整数値。
無し。
mysql_get_server_info()
char *mysql_get_server_info(MYSQL *mysql)
サーバのバージョン番号を表わす文字列を返します。
サーバのバージョン番号を表わす文字列。
無し。
mysql_info()
char * mysql_info(MYSQL *mysql)
最も最近に実行されたクエリについての情報を文字列で返します。が、
以下に挙げる構文に限ります。
他の構文では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()
は、INSERT ... VALUES
ステートメントに非
NULL
値を返します。
最も最近に実行されたクエリについての追加情報を表わす文字列。クエリに有効
な情報がない場合は NULL
ポインタ。
無し。
mysql_init()
MYSQL * mysql_init(MYSQL *mysql)
mysql_real_connect()
に適した MYSQL
オブジェクトの割り当て
または初期化を行ないます。引数が NULL
ポインタの場合、関数は新し
いオブジェクトを割り当てて初期化し返します。そうでなければオブジェクトは
初期化され、オブジェクトのアドレスが返されます。新しいオブジェクトが割り
当てられた場合、mysql_close()
はこのオブジェクトを解放します。
初期化された MYSQL*
ハンドル、または新しいオブジェクトを割り当て
るのに十分なメモリがなかった場合は NULL
ポインタ。
メモリ不足の場合は NULL
が返されます。
mysql_insert_id()
my_ulonglong mysql_insert_id(MYSQL *mysql)
前のクエリによって AUTO_INCREMENT
フィールドに生成された ID を返します。
AUTO_INCREMENT
フィールドを含むテーブルに INSERT
クエリを
実行した後で、この関数を使用してください。
注意: 前のクエリが AUTO_INCREMENT
値を生成しなかった場合、
mysql_insert_id()
は 0
を返します。後のために値を保存する必
要がある場合、値を生成するクエリの直後に mysql_insert_id()
を呼び出
すことに気をつけてください。
mysql_insert_id()
is updated after INSERT
and
UPDATE
statements that generate an AUTO_INCREMENT
value or
that set a column value to LAST_INSERT_ID(expr)
.
「6.3.6.2 その他の関数」節参照.
また、SQL LAST_INSERT_ID()
常に最後に生成された
AUTO_INCREMENT
値を含み、クエリ間でリセットされないことに注意して下
さい。その関数の値はサーバ内で保守されるからです。
前のクエリによって更新された AUTO_INCREMENT
フィールドの値。接続上
の前のクエリがない場合、クエリが AUTO_INCREMENT
値を更新しなかった
場合には 0 が返ります。
無し。
mysql_kill()
int mysql_kill(MYSQL *mysql, unsigned long pid)
pid
で指定されたスレッドを殺すようにサーバに頼みます。
成功時0。失敗時非0。
CR_COMMANDS_OUT_OF_SYNC
CR_SERVER_GONE_ERROR
CR_SERVER_LOST
CR_UNKNOWN_ERROR
mysql_list_dbs()
MYSQL_RES *mysql_list_dbs(MYSQL *mysql, const char *wild)
サーバ上の、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
CR_SERVER_LOST
CR_UNKNOWN_ERROR
mysql_list_fields()
MYSQL_RES *mysql_list_fields(MYSQL *mysql, const char *table, const char *wild)
与えられたテーブル内の、wild
引数で指定された簡易正規表現に適合する
フィールド名からなる結果セットを返します。wild
はワイルドカー
ド文字 `%' または `_' を含むことができます。また、全てのフィー
ルドに適合するように NULL
ポインタにできます。
mysql_list_fields()
はクエリ SHOW COLUMNS FROM table [LIKE
wild]
を実行するのと同様です。
注意: mysql_list_fields()
の代わりに SHOW COLUMNS FROM
tbl_name
の使用を勧めます。
mysql_free_result()
で結果セットを解放する必要があります。
成功時 MYSQL_RES
結果セット。エラーが発生した場合は NULL
。
CR_COMMANDS_OUT_OF_SYNC
CR_SERVER_GONE_ERROR
CR_SERVER_LOST
CR_UNKNOWN_ERROR
mysql_list_processes()
MYSQL_RES *mysql_list_processes(MYSQL *mysql)
現在のサーバスレッドを示す結果セットを返します。これは mysqladmin
processlist
や SHOW PROCESSLIST
クエリで
報告されるものと同じ種類の情報です。
mysql_free_result()
で結果セットを解放する必要があります。
成功時 MYSQL_RES
結果セット。失敗した場合は NULL
。
CR_COMMANDS_OUT_OF_SYNC
CR_SERVER_GONE_ERROR
CR_SERVER_LOST
CR_UNKNOWN_ERROR
mysql_list_tables()
MYSQL_RES *mysql_list_tables(MYSQL *mysql, const char *wild)
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
CR_SERVER_LOST
CR_UNKNOWN_ERROR
mysql_num_fields()
unsigned int mysql_num_fields(MYSQL_RES *result)
または
unsigned int mysql_num_fields(MYSQL *mysql)
二番目の形式は MySQL 3.23 以上では動作しません。MYSQL*
引
数を通す場合は、代わりに unsigned int mysql_field_count(MYSQL*mysql)
を使用しなくてはいけません。
結果セット中のフィールド数を返します。
注意: 結果セットへのポインタまたは接続ハンドルのいずれかからフィールドの数
を得ることができます。mysql_store_result()
または
mysql_use_result()
が NULL
を返した(つまり結果セットポイン
タが無い)場合、接続ハンドルを使用します。この場合、
mysql_field_count()
を呼び出して、mysql_store_result()
が空
でない結果を提供すべきかどうかを決定できます。これにより、クライアントプロ
グラムはクエリが SELECT
(または SELECT
に似た)ステートメン
トだったかどうかを知ることなしに、適切な行動を取ることができます。以下に示
す例はこれをどのように行なうかを説明しています。
「8.4.6.1 mysql_query()
が成功を返した後、mysql_store_result()
が NULL
を返す時があるのは何故?」節参照.
結果セット中のフィールド数を表わす符号無し整数。
無し。
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 かどうかのチェックに置き換えることです。これは何かが悪い場合にだけ起こり
ます。
mysql_num_rows()
my_ulonglong mysql_num_rows(MYSQL_RES *result)
結果セット中のレコード数を返します。
mysql_num_rows()
の使用は、結果セットを返すのに
mysql_store_result()
か mysql_use_result()
のどちらを使用す
るかに依存します。mysql_store_result()
を使用する場合、
mysql_num_rows()
はすぐに呼ぶことができます。
mysql_use_result()
を使用する場合、結果セットの全てのレコードが取り
出されるまで、mysql_num_rows()
は正しい値を返しません。
結果セットのレコード数。
無し。
mysql_options()
int mysql_options(MYSQL *mysql, enum mysql_option option, const char *arg)
特別な接続オプションを設定し、接続の振舞いに影響を与えるために使用できます。 この関数は複数のオプションを設定するために複数回呼ぶことができます。
mysql_options()
は mysql_init()
の後で、
mysql_connect()
や mysql_real_connect()
の前に呼ばれなければ
なりません。
option
引数は設定したいオプションです; arg
引数はオプション
に対する値です。オプションが整数の場合、arg
は整数値へのポインタで
す。
有効なオプション値:
オプション | 引数型 | 機能 |
MYSQL_OPT_CONNECT_TIMEOUT | unsigned int * | 接続タイムアウト(秒)。 |
MYSQL_OPT_COMPRESS | 使用しない | 圧縮クライアント/サーバプロトコルを使用する。 |
MYSQL_OPT_LOCAL_INFILE | optional pointer to uint | If no pointer is given or if pointer points to an unsigned int != 0 the command LOAD LOCAL INFILE is enabled.
|
MYSQL_OPT_NAMED_PIPE | 使用しない | NT 上の MySQL サーバへの接続に名前付パイプを使用する。 |
MYSQL_INIT_COMMAND | char * | MySQL サーバへの接続時に実行するコマンド。再接続時に自動的に再実行される。 |
MYSQL_READ_DEFAULT_FILE | char * | `my.cnf' の代わりに指定されたオプションファイルからオプションを読み込む。 |
MYSQL_READ_DEFAULT_GROUP | char * | `my.cnf' または MYSQL_READ_DEFAULT_FILE で指定されたファイルから指定されたグループのオプションを読み込む。
|
注意: MYSQL_READ_DEFAULT_FILE
と MYSQL_READ_DEFAULT_GROUP
を
使用する場合、client
グループが常に読まれます。
オプションファイル中に指定されるグループは次のオプションを含むことができま す:
connect-timeout | 接続タイムアウト(秒)。On Linux this timeout is also used for waiting for the first answer from the server. |
compress | 圧縮クライアント/サーバプロトコルを使用する。 |
database | 接続命令中でデータベースが指定されない場合、このデータベースに接続する。 |
debug | デバッグオプション |
disable-local-infile | Disable use of LOAD DATA LOCAL .
|
max_allowed_packet | Max size of packet client can read from server. |
host | デフォルトホスト名 |
init-command | MySQL サーバへの接続時に実行するコマンド。再接続時に自動的に再実行される。 |
local-infile[=(0|1)] | If no argument or argument != 0 then enable use of LOAD DATA LOCAL .
|
password | デフォルトパスワード |
pipe | NT 上の MySQL サーバへの接続に名前付パイプを使用する。 |
port | デフォルトポート番号 |
return-found-rows | UPDATE 使用時、mysql_info() が更新された行の代わりに見つかった行を返すようにする。
|
socket | デフォルトソケット番号 |
user | デフォルトユーザ |
Note that timeout
has been replaced by connect-timeout
, but
timeout
will still work for a while.
オプションファイルについてのさらなる情報は、 「4.1.2 `my.cnf' オプションファイル」節 を参照して 下さい。
成功の場合は0。未知のオプションを使用した場合は非0。
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)); }
上記は、圧縮クライアント/サーバプロトコルを使用し、my.cnf
ファイル
中の odbc
セクションから追加オプションを読むように、クライアントに
要求します。
mysql_ping()
int mysql_ping(MYSQL *mysql)
サーバへの接続が動作しているかどうかをチェックします。ダウンしている場合 は、自動的に再接続を試みます。
この関数は、長い間静かにしているクライアントが、サーバが接続をクローズし たかどうかをチェック(と再接続)するために使用できます。
サーバが生きている場合0。他の値はエラーを示します。
CR_COMMANDS_OUT_OF_SYNC
CR_SERVER_GONE_ERROR
CR_UNKNOWN_ERROR
mysql_query()
int mysql_query(MYSQL *mysql, const char *query)
NULL 終端文字列 query
で示される SQL クエリを実行します。クエリはひ
とつの SQL ステートメントでなければなりません。終端のセミコロン
(`;')や \g
をステートメントに追加すべきではありません。
mysql_query()
はバイナリデータを含むクエリには使用できません(バ
イナリデータは `\0' 文字を含むことがあります。これはクエリ文字列の
最後として解釈されます)。この場合、mysql_real_query()
を代わりに
使用してください。
If you want to know if the query should return a result set or not, you can
use mysql_field_count()
to check for this.
「8.4.3.85 mysql_field_count()
」節参照.
クエリが成功した場合は0。クエリが失敗した場合は非0。
CR_COMMANDS_OUT_OF_SYNC
CR_SERVER_GONE_ERROR
CR_SERVER_LOST
CR_UNKNOWN_ERROR
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)
host
上で動作している MySQL データベースエンジンへの接続
の確立を試みます。
mysql_get_client_info()
以外の他の API 関数を実行する前に、
mysql_real_connect()
が成功している必要があります。
mysql_real_connect()
を呼び出す前に、MYSQL
構造体を獲得ま
たは初期化するために mysql_init()
を呼ぶ必要があることに注意して
ください。
MYSQL
構造体のアドレスです。
mysql_real_connect()
を呼ぶ前に、MYSQL
構造体の初期化のため
に mysql_init()
を呼ぶ必要があります。
mysql_options()
呼び出しで多くの接続オプションを変更できます。
「8.4.3.163 mysql_options()
」節参照.
host
の値はホスト名か IP アドレスのどちらでも可能です。
host
が NULL
または文字列 "localhost"
の場合はロー
カルホストへの接続とみなされます。OS がソケットをサポートする場合(UNIX)
または名前つきパイプをサポートする場合(Windows)、サーバへの TCP/IP 接続の
代わりに使用されます。
user
パラメータはユーザの MySQL ログイン ID が入っています。
user
が NULL
の場合、現在のユーザとみなされます。Windows
ODBC 下では、現在のユーザは明示的に指定されなければなりません。UNIX 下で
は現在のログイン名が適用されます。
Windows ODBC では, カレントのユーザー名を与えなければなりません。
「8.3.2 ODBC 管理プログラムの各種項目を埋めるには?」節参照.
passwd
パラメータは user
のパスワードが入っています。
もし passwd
が NULL
の場合、空白のパスワードフィールドを持つ
user
テーブル内のレコードだけが適合チェックされます。このような方
法で、パスワードが記述されたかどうかによってユーザが異なる権限を得るよう
に、データベース管理者が MySQL 特権システムを設定することができ
ます。
注意: mysql_connect()
を呼び出す前に passwd
を暗号化しない
でください。パスワードの暗号化はクライアント API で自動的に処理されます。
db
が NULL
でない場合、接続はこの値をデフォルトデータベー
スにセットします。
port
が 0 でない場合、値は TCP/IP 接続のポート番号として使用され
ます。host
パラメータが接続のタイプを決定することに注意してくださ
い。
unix_socket
が NULL
でない場合、文字列は使用されるソケット
または名前つきパイプを記述します。host
パラメータが接続のタイプを
決定することに注意してください。
フラグ名 | フラグの意味 |
CLIENT_COMPRESS | Use compression protocol. |
CLIENT_FOUND_ROWS | 影響された行数ではなく見つかった行数を返します |
CLIENT_IGNORE_SPACE | Allow spaces after function names. Makesall functions names reserved words. |
CLIENT_INTERACTIVE | Allow interactive_timeout seconds(instead of wait_timeout seconds) of inactivity before closing the connection.
|
CLIENT_NO_SCHEMA | db_name.tbl_name.col_name を許しません。これは ODBC のためです; その構文を使用した場合、パーサがエラーを生成します。これはいくつかの ODBC プログラムのバグのトラップに役立ちます。
|
CLIENT_COMPRESS | 圧縮プロトコルを使用します |
CLIENT_ODBC | クライアントが ODBC クライアント。これは mysqld をさらに ODBC-フレンドリに変更します。
|
CLIENT_SSL | Use SSL (encrypted protocol). |
mysql_real_connect()
の最初の引数に NULL
ポインタを記述す
ることもできます。これは C API が接続構造体のメモリを割り当て、
mysql_close()
呼び出し時に自動的に解放されます。この方法の不利な
点は、接続が失敗した場合に mysql_real_connect()
からのエラーメッ
セージを取り出すことができないことです。
最初の引数が NULL
ポインタでない場合は、存在する MYSQL
構
造体のアドレスであるべきです。
接続が成功した場合は MYSQL*
接続ハンドルです。接続が失敗した場合
は C NULL
ポインタです。
接続に成功すると、戻り値はその最初のパラメータの値と同じです。
CR_CONN_HOST_ERROR
CR_CONNECTION_ERROR
CR_IPSOCK_ERROR
CR_OUT_OF_MEMORY
CR_SOCKET_CREATE_ERROR
CR_UNKNOWN_HOST
CR_VERSION_ERROR
--old-protocol
オプション付きで開始していない新
しいサーバに接続する場合に発生します。
CR_NAMEDPIPEOPEN_ERROR
CR_NAMEDPIPEWAIT_ERROR
CR_NAMEDPIPESETSTATE_ERROR
CR_SERVER_LOST
connect_timeout
> 0 and it took longer then connect_timeout
seconds to connect to the server or if the server died while executing the
init-command
.
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)); }
By using mysql_options()
the MySQL library will read the
[client]
and [your_prog_name]
sections in the `my.cnf'
file which will ensure that your program will work, even if someone has
set up MySQL in some non-standard way.
Note that upon connection, mysql_real_connect()
sets the reconnect
flag (part of the MYSQL
structure) to a value of 1
. This
flag indicates, in the event that a query cannot be performed because
of a lost connection, to try reconnecting to the server before giving up.
mysql_real_escape_string()
unsigned long mysql_real_escape_string(MYSQL *mysql, char *to, const char *from, unsigned long length)
This function is used to create a legal SQL string that you can use in a SQL statement. 「6.1.1.1 文字列」節参照.
from
の文字列を、SQL ステートメントとしてサーバに送ることができる
ように、現在のキャラクタ・セットを考慮しながら変換します。
結果は to
に入り、終端 null 文字を追加します。
変換される文字列は `NUL' (ASCII 0), `\n', `\r', `\',
`'', `"', Control-Z です。( 「6.1.1 文字列と数値をどのように書くか?」節参照).
(Strictly speaking, MySQL requires only that backslash and the quote
character used to quote the string in the query be escaped. This function
quotes the other characters to make them easier to read in log files.)
from
で示される文字列
はlength
バイト長でなければなりません。
to
バッファには少なくとも length*2+1
バイト長を割り当てる
必要があります。(最悪の場合、それぞれの文字が2バイトに変換されることがあ
り、さらに終端 null バイトのための場所が必要です。)
mysql_real_escape_string()
が復帰するとき、to
の内容は NUL
終端文字列になります。
戻り値は変換された文字列の長さです。終端 null 文字は含みません。
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()
のように働きますが、最初の引数の終りの null へのポイ
ンタを返します。
to
へ置かれた値の長さ。終端 null 文字は含みません。
無し。
mysql_real_query()
int mysql_real_query(MYSQL *mysql, const char *query, unsigned long length)
query
で示される SQL クエリを実行します。これは length
バ
イト長です。クエリはひとつの SQL ステートメントでなければなりません。終端
のセミコロン(`;')や \g
をステートメントに追加すべきではありま
せん。
バイナリデータを含むクエリは mysql_real_query()
を使
用しなければなりません。バイナリデータは `\0' 文字を含むこと
があるからです。
また、mysql_real_query()
は mysql_query()
よりも速いです。
クエリの strlen()
を呼ばないからです。
If you want to know if the query should return a result set or not, you can
use mysql_field_count()
to check for this.
「8.4.3.85 mysql_field_count()
」節参照.
クエリが成功した場合は0。クエリが失敗した場合は非0。
CR_COMMANDS_OUT_OF_SYNC
CR_SERVER_GONE_ERROR
CR_SERVER_LOST
CR_UNKNOWN_ERROR
mysql_reload()
int mysql_reload(MYSQL *mysql)
MySQL サーバに、アクセス権テーブルを再読み込みするように依頼し
ます。接続されたユーザは RELOAD
権限を持つ必要があります。
この関数は推奨されません。代わりに、SQL FLUSH PRIVILEGES
ステートメ
ントを発行する mysql_query()
の使用が推奨されます。
成功時0。失敗時非0。
CR_COMMANDS_OUT_OF_SYNC
CR_SERVER_GONE_ERROR
CR_SERVER_LOST
CR_UNKNOWN_ERROR
mysql_row_seek()
MYSQL_ROW_OFFSET mysql_row_seek(MYSQL_RES *result, MYSQL_ROW_OFFSET offset)
レコードカーソルをクエリ結果セット中の絶対レコードに設定します。これは、結
果セット構造体がクエリのすべての結果を持っていることを要求します。そのため、
mysql_row_seek()
は mysql_store_result()
と共にだけ使用でき、
mysql_use_result()
と共には使用できません。
オフセットは mysql_row_tell()
または mysql_row_seek()
呼びだ
しからの戻り値であるべきです。この値は単純なレコード番号ではありません;レ
コード番号を使用して結果セット内のレコードにシークしたい場合は、
mysql_data_seek()
を代わりに使用してください。
レコードカーソルの前の値。この値はその後の mysql_row_seek()
呼びだ
しに渡すことができます。
無し。
mysql_row_tell()
MYSQL_ROW_OFFSET mysql_row_tell(MYSQL_RES *result)
最後の mysql_fetch_row()
についてレコードカーソルの現在の位置を返します。
この値は mysql_row_seek()
への引数として使用できます。
mysql_row_tell()
は mysql_store_result()
の後にだけ使用すべ
きで、mysql_use_result()
の後には使用すべきではありません。
行カーソルの現在のオフセット。
無し。
mysql_select_db()
int mysql_select_db(MYSQL *mysql, const char *db)
mysql
で示される現在の接続に、デフォルト(現在の)データベースとし
て db
で示されるデータベースを使用するように指示します。以降のク
エリでは、明示的にデータベースを指定しないテーブル参照について、このデー
タベースがデフォルトになります。
接続されたユーザがデータベースを使用する権限を持っていると証明されなけれ
ば、mysql_select_db()
は失敗します。
成功時0。失敗時非0。
CR_COMMANDS_OUT_OF_SYNC
CR_SERVER_GONE_ERROR
CR_SERVER_LOST
CR_UNKNOWN_ERROR
mysql_shutdown()
int mysql_shutdown(MYSQL *mysql)
データベースサーバにシャットダウンするように要求します。接続されたユーザ
は SHUTDOWN
権限を持っている必要があります。
成功時0。失敗時非0。
CR_COMMANDS_OUT_OF_SYNC
CR_SERVER_GONE_ERROR
CR_SERVER_LOST
CR_UNKNOWN_ERROR
mysql_stat()
char *mysql_stat(MYSQL *mysql)
mysqladmin status
で提供されるのと同様の情報を文字列として返しま
す。これは秒での uptime と、実行中のスレッド数、問い合わせ数、再読み込み
数、オープンテーブル数を含みます。
サーバ状態を表わす文字列。エラーが発生した場合 NULL
。
CR_COMMANDS_OUT_OF_SYNC
CR_SERVER_GONE_ERROR
CR_SERVER_LOST
CR_UNKNOWN_ERROR
mysql_store_result()
MYSQL_RES *mysql_store_result(MYSQL *mysql)
データを取り出すクエリ(SELECT
, SHOW
, DESCRIBE
,
EXPLAIN
)が成功する毎に、mysql_store_result()
または
mysql_use_result()
を呼び出す必要があります。
You don't have to call mysql_store_result()
or
mysql_use_result()
for other queries, but it will not do any
harm or cause any notable performance if you call mysql_store_result()
in all cases. You can detect if the query didn't have a result set by
checking if mysql_store_result()
returns 0 (more about this later one).
If you want to know if the query should return a result set or not, you can
use mysql_field_count()
to check for this.
「8.4.3.85 mysql_field_count()
」節参照.
mysql_store_result()
はクエリのすべての結果をクライアントへ読み込み、
MYSQL_RES
構造体を割り当て、この構造体に結果を配置します。
mysql_store_results()
returns a null pointer if the query didn't return
a result sets (If the query was, for example, an INSERT
statement).
mysql_store_results()
returns also null pointer if reading of the
result set failed. You can check if you got an error by checking if
mysql_error()
doesn't return a null pointer, if
mysql_errno()
returns <> 0 or if mysql_field_count()
returns <> 0.
返されるレコードが無い場合、空の結果セットが返されます。 (空の結果セットは
NULL
戻り値とは異なります。)
一度 mysql_store_result()
を呼び出して null ポインターでない
結果を得る事ができたら、結果セット中にいくつのレ
コードがあるかを見つけるために、mysql_num_rows()
を呼び出すことがで
きます。
結果セットからレコードを取り出すために mysql_fetch_row()
を呼び出す
ことができます。また、結果セット内の現在のレコード位置を設定/取得するため
に mysql_row_seek()
と mysql_row_tell()
を呼び出すことができ
ます。
一度結果セットで行なうと、mysql_free_result()
を呼び出す必要があ
ります。
「8.4.6.1 mysql_query()
が成功を返した後、mysql_store_result()
が NULL
を返す時があるのは何故?」節参照.
結果の MYSQL_RES
結果構造体。エラーがある場合 NULL
。
CR_COMMANDS_OUT_OF_SYNC
CR_OUT_OF_MEMORY
CR_SERVER_GONE_ERROR
CR_SERVER_LOST
CR_UNKNOWN_ERROR
mysql_thread_id()
unsigned long mysql_thread_id(MYSQL *mysql)
現在の接続のスレッド ID を返します。この値は、スレッドを殺すための
mysql_kill()
への引数として使用できます。
接続が失われて、mysql_ping()
で再接続した場合、スレッド ID は変更さ
れます。これはスレッド ID を後で使うために取得して格納すべきではないことを
意味します。必要な時にそれを取得すべきです。
現在の接続のスレッド ID。
無し。
mysql_use_result()
MYSQL_RES *mysql_use_result(MYSQL *mysql)
データを取り出すクエリ(SELECT
, SHOW
, DESCRIBE
,
EXPLAIN
)が成功する毎に、 mysql_store_result()
または
mysql_use_result()
を呼び出す必要があります。
mysql_use_result()
は結果セット検索を開始しますが,
mysql_store_result()
のように、実際にクライアントに結果セットを読み
取りません. 代わりに、各レコードは mysql_fetch_row()
呼びだしが行な
われることにより、個々に取り出されます。
mysql_use_result()
はクエリの結果を、一時テーブルやローカルバッファ
に格納すること無く、サーバから直接読み込みます。これは
mysql_store_result()
よりもいくらか速く、少ないメモリを使用します。
この場合、クライアントは現在の行と接続バッファ
( max_allowed_packet
bytes まで増加する ) のメモリだけを割り当てます。
一方、クライアント側で各行に
ついて多くの処理を行なう場合や、ユーザが ^S
(スクロール停止) を入
力できるような画面に出力を送る場合は、mysql_use_result()
を使用す
べきではありません。これはサーバと連携しており、他のスレッドが
データが取り出されるテーブルを更新する事を邪魔します。
mysql_use_result()
使用時、NULL
値を取り出すまで
mysql_fetch_row()
を実行する必要があります。そうしないと、次のク
エリは前のクエリから結果を取り出します。これを忘れると、C API はエラー
Commands out of sync; You can't run this command now
を与えます!
mysql_use_result()
から返される結果では、
mysql_data_seek()
, mysql_row_seek()
,
mysql_row_tell()
, mysql_num_rows()
,
mysql_affected_rows()
を使用できません。
また、mysql_use_result()
が終了するまで他のクエリの発行もできませ
ん。(全ての行をフェッチした後に、フェッチされた行数を知るために
mysql_num_rows
を呼び出すことができます。)
一度結果セットで行なうと、mysql_free_result()
を呼び出す必要があ
ります。
結果の MYSQL_RES
結果構造体。エラーがある場合 NULL
。
CR_COMMANDS_OUT_OF_SYNC
CR_OUT_OF_MEMORY
CR_SERVER_GONE_ERROR
CR_SERVER_LOST
CR_UNKNOWN_ERROR
You need to use the following functions when you want to create a threaded client. 「8.4.8 スレッドクライアントを作る方法」節参照.
my_init()
void my_init(void)
This function needs to be called once in the program before calling any
MySQL function. This initialises some global variables that MySQL
needs. If you are using a thread-safe client library, this will also
call mysql_thread_init()
for this thread.
This is automatically called by mysql_init()
,
mysql_server_init()
and mysql_connect()
.
None.
mysql_thread_init()
my_bool mysql_thread_init(void)
This function needs to be called for each created thread to initialise thread-specific variables.
This is automatically called by my_init()
and mysql_connect()
.
None.
mysql_thread_end()
void mysql_thread_end(void)
This function needs to be called before calling pthread_exit()
to
free memory allocated by mysql_thread_init()
.
Note that this function is not invoked automatically by the client library. It must be called explicitly to avoid a memory leak.
None.
mysql_thread_safe()
unsigned int mysql_thread_safe(void)
This function indicates whether the client is compiled as thread-safe.
1 is the client is thread-safe, 0 otherwise.
You must use the following functions if you want to allow your application to be linked against the embedded MySQL server library. 「8.4.9 libmysqld, the Embedded MySQL Server Library」節参照.
If the program is linked with -lmysqlclient
instead of
-lmysqld
, these functions do nothing. This makes it
possible to choose between using the embedded MySQL server and
a stand-alone server without modifying any code.
mysql_server_init()
int mysql_server_init(int argc, char **argv, char **groups)
This function must be called once in the program using the
embedded server before calling any other MySQL function. It starts up
the server and initialises any subsystems (mysys
, InnoDB, etc.)
that the server uses. If this function is not called, the program will
crash. If you are using the DBUG package that comes with MySQL, you
should call this after you have called MY_INIT()
.
The argc
and argv
arguments are analogous to the arguments
to main()
. The first element of argv
is ignored (it
typically contains the program name). For convenience, argc
may
be 0
(zero) if there are no command-line arguments for the
server. mysql_server_init()
makes a copy of the arguments so
it's safe to destroy argv
or groups
after the call.
The NULL
-terminated list of strings in groups
selects which groups in the option files will be active.
「4.1.2 `my.cnf' オプションファイル」節参照. For convenience, groups
may be
NULL
, in which case the [server]
and [emedded]
groups
will be active.
#include <mysql.h> #include <stdlib.h> static char *server_args[] = { "this_program", /* this string is not used */ "--datadir=.", "--key_buffer_size=32M" }; static char *server_groups[] = { "embedded", "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; }
0 if okay, 1 if an error occurred.
mysql_server_end()
void mysql_server_end(void)
This function must be called once in the program after all other MySQL functions. It shuts down the embedded server.
None.
mysql_query()
が成功を返した後、mysql_store_result()
が NULL
を返す時があるのは何故?
mysql_query()
の呼び出しが成功した後に
mysql_store_result()
が NULL
を返すことがあります。これが
起こったとき、次の条件のどれかの発生を意味します:
malloc()
が失敗した (例えば、結果セットが大き過ぎた場合)。
INSERT
, UPDATE
, DELETE
)。
ステートメントが空でない結果を提供するかどうかは
mysql_field_count()
の呼び出しによっていつでもチェックできます。
mysql_field_count()
が 0 を返す場合、結果は空で最後のクエリは値を
返さないステートメントです (例えば、INSERT
や DELETE
)。
mysql_field_count()
が非 0 値を返す場合、ステートメントは空でない
結果を提供します。
例はmysql_field_count()
関数の説明を参照してください。
mysql_error()
または mysql_errno()
を呼び出すことによって
エラーのテストもできます。
クエリによって返される結果セットに加えて、次の情報も得ることができます:
mysql_affected_rows()
は、INSERT
, UPDATE
または
DELETE
を行なった時の最後のクエリで、影響された行数を返します。
WHERE
節がない DELETE
が使用されて、テーブルが切り詰められ
た場合は例外です。これはとても速いです! この場合、
mysql_affected_rows()
は影響された行数を 0 と返します。
mysql_num_rows()
は結果セットのレコード数を返します。
mysql_store_result()
では、mysql_num_rows()
は
mysql_store_result()
が復帰したすぐ後に呼び出すことができます。
mysql_use_result()
では、mysql_num_rows()
は
mysql_fetch_row()
ですべてのレコードを取り出した後にだけ呼ぶ出すこ
とができます。
mysql_insert_id()
は、AUTO_INCREMENT
インデックスを持つテー
ブルに行を挿入した最後のクエリによって生成された ID を返します。
「8.4.3.130 mysql_insert_id()
」節参照.
LOAD DATA INFILE...
, INSERT INTO ...
SELECT ...
, UPDATE
) は追加情報を返します。結果は
mysql_info()
で返されます。
返す文字列の形式については、mysql_info()
の説明を参照してください。
mysql_info()
は追加情報がない場
合は NULL
ポインタを返します。
AUTO_INCREMENT
属性を持つ項目を含むテーブルにレコードを挿入する場
合、mysql_insert_id()
関数で与えられた ID を得ることができます。
mysql_query()
に渡すクエリ文字列内のLAST_INSERT_ID()
関数
を使用することでも、ID を取り出すことができます。
次のコードを実行することで、AUTO_INCREMENT
インデックスが使用され
たかどうかチェックできます。これは、クエリが AUTO_INCREMENT
イン
デックスを伴う INSERT
だったかどうかもチェックできます:
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 を挿入しようとする場合、次で行なうことができます:
INSERT INTO foo (auto,text) VALUES(NULL,'text'); # generate ID by inserting NULL INSERT INTO foo2 (id,text) VALUES(LAST_INSERT_ID(),'text'); # use ID in second table
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
) を含める必要があることを意味します。
If you compile MySQL clients that you've written yourself or that
you obtain from a third-party, they must be linked using the
-lmysqlclient -lz
option on the link command. You may also need to
specify a -L
option to tell the linker where to find the library. For
example, if the library is installed in `/usr/local/mysql/lib', use
-L/usr/local/mysql/lib -lmysqlclient -lz
on the link command.
For clients that use MySQL header files, you may need to specify a
-I
option when you compile them (for example,
-I/usr/local/mysql/include
), so the compiler can find the header
files.
To make the above simpler on Unix we have provied the
mysql_config
script for you. 「4.8.9 mysql_config
, Get compile options for compiling clients」節参照.
You can use this to compile a MySQL client by as follows:
CFG=/usr/local/mysql/bin/mysql_config sh -c "gcc -o progname `$CFG --cflags` progname.c `$CFG --libs`"
The sh -c
is need to get the shell to not threat the output from
mysql_config
as one word.
クライアントは `ほとんど' スレッド安全です。一番大きな問題は
`net.c' (ソケットから読み込みをするサブルーチンを含むファイル) が割
り込み安全でないことです。これは、サーバからの長い読み込みを中断できるよ
うに、自身のアラームを持ちたいだろうという考慮で行なわれました。
If you
install interrupt handlers for the SIGPIPE
interrupt,
the socket handling should be thread-safe.
われわれの Web site で公開している古いバイナリ配布では、 標準クライアントライブラリはスレッドオプションでコンパイルされていません。 (the Windows binaries are by default compiled to be thread safe). Newer binary distributions should have both a normal and a thread-safe client library.
スレッド安全クライアント(MySQLサーバーとの通信時に、
他のスレッドがクライアントのスレッドに interrupt をかけたり、
タイムアウトをセットしたりする)
を得るためには、-lmysys
, -lstring
,
-ldbug
ライブラリとサーバが使用する net_serv.o
を使用しま
す。
If you don't need interrupts or timeouts, you can just compile a
thread-safe client library (mysqlclient_r)
and use this. 「8.4 MySQL C API」節参照. In this case you don't have to worry about the
net_serv.o
object file or the other MySQL libraries.
スレッドクライアントを使用する時、`thr_alarm.c' ルーチンを大いに使
用できます。mysys
ライブラリからのルーチンを使用する場合、覚えて
おかなければならないことは my_init()
を最初に呼ぶことだけです!
mysql_real_connect()
を除く全ての関数は現在スレッド安全です。スレッ
ド安全クライアントライブラリをコンパイルし、それをスレッド安全なマナーで使
用するための方法を、次の注意で説明します。(この
mysql_real_connect()
についての注意は、実際には
mysql_connect()
にも有効です。しかし mysql_connect()
は推奨
されませんので、とにかく mysql_real_connect()
を使用すべきです。)
mysql_real_connect()
をスレッド安全にするためには、クライアントを次の
コマンドで再コンパイルする必要があります:
shell> ./configure --enable-thread-safe-client
This will create a thread-safe client library libmysqlclient_r
.
--enable-thread-safe-client
. This library is thread safe per
connection. You can let two threads share the same connection as long
as you do the following:
mysql_query()
と mysql_store_result()
の間
で、他のスレッドが同じ接続を使用しないことを確実にする必要があります。
mysql_store_result()
で取り出された別々の結果セッ
トにアクセスできます。
mysql_use_result
を使用する場合、結果セットがクローズされるまで、他
のスレッドが同じ接続上で何も尋ねないことを確実にする必要があります。
However, it really is best for threaded clients that share the same
connection to use mysql_use_result()
.
mysql_query()
and
mysql_store_result()
call combination. Once
mysql_store_result()
is ready, the lock can be released and other
threads may query the same connection.
pthread_mutex_lock()
and pthread_mutex_unlock()
to
establish and release a mutex lock.
You need to know the following if you have a thread that is calling MySQL functions which did not create the connection to the MySQL database:
When you call mysql_init()
or mysql_connect()
, MySQL will
create a thread-specific variable for the thread that is used by the
debug library (among other things).
If you call a MySQL function, before the thread has
called mysql_init()
or mysql_connect()
, the thread will
not have the necessary thread-specific variables in place and you are
likely to end up with a core dump sooner or later.
The get things to work smoothly you have to do the following:
my_init()
at the start of your program if it calls
any other MySQL function before calling mysql_real_connect()
.
mysql_thread_init()
in the thread handler before calling
any MySQL function.
mysql_thread_end()
before calling
pthread_exit()
. This will free the memory used by MySQL
thread-specific variables.
You may get some errors because of undefined symbols when linking your
client with libmysqlclient_r
. In most cases this is because you haven't
included the thread libraries on the link/compile line.
The embedded MySQL server library makes it possible to run a full-featured MySQL server inside the client application. The main benefits are increased speed and more simple management for embedded applications.
The API is identical for the embedded MySQL version and the client/server version. To change an old threaded application to use the embedded library, you normally only have to add calls to the following functions:
Function | When to call |
mysql_server_init() | Should be called before any other MySQL function is called, preferably early in the main() function.
|
mysql_server_end() | Should be called before your program exits. |
mysql_thread_init() | Should be called in each thread you create that will access MySQL. |
mysql_thread_end() | Should be called before calling pthread_exit()
|
Then you must link your code with `libmysqld.a' instead of `libmysqlclient.a'.
The above mysql_server_xxx
functions are also included in
`libmysqlclient.a' to allow you to change between the embedded and the
client/server version by just linking your application with the right
library. 「8.4.5.1 mysql_server_init()
」節参照.
libmysqld
To get a libmysqld
library you should configure MySQL with the
--with-embedded-server
option.
When you link your program with libmysqld
, you must also include
the system-specific pthread
libraries and some libraries that
the MySQL server uses. You can get the full list of libraries by executing
mysql_config --libmysqld-libs
.
The correct flags for compiling and linking a threaded program must be used, even if you do not directly call any thread functions in your code.
The embedded server has the following limitations:
Some of these limitations can be changed by editing the `mysql_embed.h' include file and recompiling MySQL.
The following is the recommended way to use option files to make it easy to switch between a client/server application and one where MySQL is embedded. 「4.1.2 `my.cnf' オプションファイル」節参照.
[server]
section. These will be read by
both MySQL versions.
[mysqld]
section.
[embedded]
section.
[ApplicationName_SERVER]
section.
This example program and makefile should work without any changes on a Linux or FreeBSD system. For other operating systems, minor changes will be needed. This example is designed to give enough details to understand the problem, without the clutter that is a necessary part of a real application.
To try out the example, create an `test_libmysqld' directory at the same level as the mysql-4.0 source directory. Save the `test_libmysqld.c' source and the `GNUmakefile' in the directory, and run GNU `make' from inside the `test_libmysqld' directory.
`test_libmysqld.c'
/* * A simple example client, using the embedded MySQL server library */ #include <mysql.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> MYSQL *db_connect(const char *dbname); void db_disconnect(MYSQL *db); void db_do_query(MYSQL *db, const char *query); const char *server_groups[] = { "test_libmysqld_SERVER", "embedded", "server", NULL }; int main(int argc, char **argv) { MYSQL *one, *two; /* mysql_server_init() must be called before any other mysql * functions. * * You can use mysql_server_init(0, NULL, NULL), and it will * initialise the server using groups = { * "server", "embedded", NULL * }. * * In your $HOME/.my.cnf file, you probably want to put: [test_libmysqld_SERVER] language = /path/to/source/of/mysql/sql/share/english * You could, of course, modify argc and argv before passing * them to this function. Or you could create new ones in any * way you like. But all of the arguments in argv (except for * argv[0], which is the program name) should be valid options * for the MySQL server. * * If you link this client against the normal mysqlclient * library, this function is just a stub that does nothing. */ mysql_server_init(argc, argv, (char **)server_groups); one = db_connect("test"); two = db_connect(NULL); db_do_query(one, "SHOW TABLE STATUS"); db_do_query(two, "SHOW DATABASES"); mysql_close(two); mysql_close(one); /* This must be called after all other mysql functions */ mysql_server_end(); exit(EXIT_SUCCESS); } static void die(MYSQL *db, char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); (void)putc('\n', stderr); if (db) db_disconnect(db); exit(EXIT_FAILURE); } MYSQL * db_connect(const char *dbname) { MYSQL *db = mysql_init(NULL); if (!db) die(db, "mysql_init failed: no memory"); /* * Notice that the client and server use separate group names. * This is critical, because the server will not accept the * client's options, and vice versa. */ mysql_options(db, MYSQL_READ_DEFAULT_GROUP, "test_libmysqld_CLIENT"); if (!mysql_real_connect(db, NULL, NULL, NULL, dbname, 0, NULL, 0)) die(db, "mysql_real_connect failed: %s", mysql_error(db)); return db; } void db_disconnect(MYSQL *db) { mysql_close(db); } void db_do_query(MYSQL *db, const char *query) { if (mysql_query(db, query) != 0) goto err; if (mysql_field_count(db) > 0) { MYSQL_RES *res; MYSQL_ROW row, end_row; int num_fields; if (!(res = mysql_store_result(db))) goto err; num_fields = mysql_num_fields(res); while ((row = mysql_fetch_row(res))) { (void)fputs(">> ", stdout); for (end_row = row + num_fields; row < end_row; ++row) (void)printf("%s\t", row ? (char*)*row : "NULL"); (void)fputc('\n', stdout); } (void)fputc('\n', stdout); } else (void)printf("Affected rows: %lld\n", mysql_affected_rows(db)); return; err: die(db, "db_do_query failed: %s [%s]", mysql_error(db), query); }
`GNUmakefile'
# This assumes the MySQL software is installed in /usr/local/mysql inc := /usr/local/mysql/include/mysql lib := /usr/local/mysql/lib # If you have not installed the MySQL software yet, try this instead #inc := $(HOME)/mysql-4.0/include #lib := $(HOME)/mysql-4.0/libmysqld CC := gcc CPPFLAGS := -I$(inc) -D_THREAD_SAFE -D_REENTRANT CFLAGS := -g -W -Wall LDFLAGS := -static # You can change -lmysqld to -lmysqlclient to use the # client/server library LDLIBS = -L$(lib) -lmysqld -lz -lm -lcrypt ifneq (,$(shell grep FreeBSD /COPYRIGHT 2>/dev/null)) # FreeBSD LDFLAGS += -pthread else # Assume Linux LDLIBS += -lpthread endif # This works for simple one-file test programs sources := $(wildcard *.c) objects := $(patsubst %c,%o,$(sources)) targets := $(basename $(sources)) all: $(targets) clean: rm -f $(targets) $(objects) *.core
The MySQL source code is covered by the GNU GPL license
( 「H GNU General Public License」節参照). One result of this is that any program
which includes, by linking with libmysqld
, the MySQL
source code must be released as free software (under a license
compatible with the GPL).
We encourage everyone to promote free software by releasing code under the GPL or a compatible license. For those who are not able to do this, another option is to purchase a commercial licence for the MySQL code from MySQL AB. For details, please see 「1.4.3 MySQL Licenses」節.
MySQL Connector/C++ (or MySQL++
) is the official MySQL API for C++. More
information can be found at http://www.mysql.com/products/mysql++/.
You can compile the MySQL Windows source with Borland C++ 5.02. (The Windows source includes only projects for Microsoft VC++, for Borland C++ you have to do the project files yourself.)
One known problem with Borland C++ is that it uses a different structure
alignment than VC++. This means that you will run into problems if you
try to use the default libmysql.dll
libraries (that was compiled
with VC++) with Borland C++. You can do one of the following to avoid
this problem.
mysql_init()
with NULL
as an argument, not a
pre-allocated MYSQL struct.
There are 2 supported JDBC drivers for MySQL (the Connector/J driver and the Resin JDBC driver). You can find a copy of the Connector/J driver at http://www.mysql.com/products/connector-j/ and the Resin driver at http://www.caucho.com/projects/jdbc-mysql/index.xtp For documentation consult any JDBC documentation and the driver's own documentation for MySQL-specific features.
MySQLdb provides MySQL support for Python, compliant with the Python DB API version 2.0. It can be found at http://sourceforge.net/projects/mysql-python/.
MySQLtcl is a simple API for accessing a MySQL database server from the Tcl programming language. It can be found at http://www.xdobry.de/mysqltcl/.
Eiffel MySQL is an interface to the MySQL database server using the Eiffel programming language, written by Michael Ravits. It can be found at http://efsa.sourceforge.net/archive/ravits/mysql.htm.
You can also find this at: http://www.netpedia.net/hosting/newplayer/
以下のサイトに、Ruby の MySQL インターフェースがあります。
www.tmtm.org とみたまさひろ氏の Web ページ
Go to the first, previous, next, last section, table of contents.