当前位置:Gxlcms > mysql > MySQL中的CAPI

MySQL中的CAPI

时间:2021-07-01 10:21:17 帮助过:39人阅读

#include my_global.h#include mysql.hint main(int argc, char **argv){ MYSQL *conn; MYSQL_RES *result; MYSQL_ROW row; int num_fields; int i; conn = mysql_init(NULL); mysql_real_connect(conn, localhost, user, passwd, test, 0, NULL, 0); mysql_

  1. #include <my_global.h>
  2. #include <mysql.h>
  3. int main(int argc, char **argv)
  4. {
  5. MYSQL *conn;
  6. MYSQL_RES *result;
  7. MYSQL_ROW row;
  8. int num_fields;
  9. int i;
  10. conn = mysql_init(NULL);
  11. mysql_real_connect(conn, "localhost", "user", "passwd", "test", 0, NULL, 0);
  12. mysql_query(conn, "select * from student");
  13. result = mysql_store_result(conn);
  14. num_fields = mysql_num_fields(result);
  15. while ((row = mysql_fetch_row(result)))
  16. {
  17. for(i = 0; i < num_fields; i++)
  18. {
  19. printf("%s ", row[i] ? row[i] : "NULL");
  20. }
  21. printf("\n");
  22. }
  23. mysql_free_result(result);
  24. mysql_close(conn);
  25. }</mysql.h></my_global.h>

注释:

MYSQL* conn;

conn = mysql_init(NULL);
初始化一个MYSQL结构体,这个结构体就是一个数据库连接句柄。


mysql_real_connect(conn, "localhost", "user", '"passwd", "test", 0, NULL, 0) ;

建立一个到mysql数据库的链接。函数参数 链接句柄、主机名、用户、密码、数据库名、端口、unix套接字和客户端标志。


mysql_query(conn, "create database testdb");

mysql_query执行指定为“以Null终结的字符串”的SQL查询。


MYSQL_RES *result;

result = mysql_store_result(conn);

检索完整的结果集至客户端。


MYSQL_ROW row;

row = mysql_fetch_row(result)

获取结果集中的一行

mysql_num_fields(result);

返回结果集中的列数


for(i = 0; i < num_fields; i++){

printf("%s ", row[i] ? row[i] : "NULL");

}

输出一行数据


mysql_close(conn);

关闭数据库链接。


printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));

错误处理。mysql_errno返回上次调用的MySQL函数的错误编号。

mysql_error返回上次调用的MySQL函数的错误消息。


除非作了其他规定,返回指针的函数将返回非Null值,以指明成功,或返回NULL值以指明出错。

返回整数的函数将返回0以指明成功,或返回非0值以指明出错。注意,非0值仅表明这点。

除非在函数描述中作了其他说明,不要对非0值进行测试:
if (result) /* correct */
... error ...


if (result < 0) /* incorrect */
... error ...

if (result == -1) /* incorrect */

人气教程排行