Database Reference
In-Depth Information
We end this brief programwith the
mysql_close()
function to end the MySQL ses-
sion and to disconnect from MySQL. The final closing curly brace ends the main func-
tion.
Complete Minimal C API Program
It's easier to explainthe components of a program step by step as I have done here, but
seeing even a small program in pieces can be confusing. So here it is again in its entirety:
#include <stdio.h>
#include "/usr/include/mysql/mysql.h"
int
main
(
int
argc
,
char
*
argv
[ ])
{
MYSQL
*
mysql
;
MYSQL_RES
*
result
;
MYSQL_ROW row
;
if
(
mysql_init
(
mysql
) ==
NULL
) {
fprintf
(
stderr
,
"Cannot Initialize MySQL"
);
return
1
;
}
if
(!
mysql_real_connect
(
mysql
,
"localhost"
,
"public_api"
,
"pwd_123"
,
"rookery"
,
0
,
NULL
,
0
)) {
fprintf
(
stderr
,
"%d: %s
\n
"
,
mysql_errno
(
mysql
),
mysql_error
(
mysql
));
return
1
;
}
if
(
mysql_query
(
mysql
,
"SELECT common_name, scientific_name FROM
birds"
)) {
fprintf
(
stderr
,
"%d: %s
\n
"
,
mysql_errno
(
mysql
),
mysql_error
(
mysql
));
}
else
{
result
=
mysql_store_result
(
mysql
);
while
(
row
=
mysql_fetch_row
(
result
)) {
printf
(
"\%s - \%s
\n
"
,
row
[
0
],
row
[
1
]);
}
mysql_free_result
(
result
);
}
mysql_close
(
mysql
);
return
0
;
}