01 | #if defined(_WIN32) || defined(_WIN64) //为了支持windows平台上的编译 |
02 | #include <windows.h> |
03 | #endif |
04 | #include <stdio.h> |
05 | #include <stdlib.h> |
06 | #include "mysql.h" |
07 | |
08 | //定义数据库操作的宏,也可以不定义留着后面直接写进代码 |
09 | #define SELECT_QUERY "show tables;" |
10 | |
11 | int main( int argc, char **argv) //char **argv 相当于 char *argv[] |
12 | { |
13 | MYSQL mysql,*handle; //定义数据库连接的句柄,它被用于几乎所有的MySQL函数 |
14 | MYSQL_RES *result; //查询结果集,结构类型 |
15 | MYSQL_FIELD *field ; //包含字段信息的结构 |
16 | MYSQL_ROW row ; //存放一行查询结果的字符串数组 |
17 | char querysql[160]; //存放查询sql语句字符串 |
18 | //初始化 |
19 | mysql_init(&mysql); |
20 | //连接数据库 |
21 | if (!(handle = mysql_real_connect(&mysql, "localhost" , "user" , "pwd" , "dbname" ,0,NULL,0))) { |
22 | fprintf (stderr, "Couldn't connect to engine!\n%s\n\n" ,mysql_error(&mysql)); |
23 | } |
24 | sprintf (querysql,SELECT_QUERY, atoi (argv[1])); |
25 | //查询数据库 |
26 | if (mysql_query(handle,querysql)) { |
27 | fprintf (stderr, "Query failed (%s)\n" ,mysql_error(handle)); |
28 | } |
29 | //存储结果集 |
30 | if (!(result=mysql_store_result(handle))) { |
31 | fprintf (stderr, "Couldn't get result from %s\n" , mysql_error(handle)); |
32 | } |
33 | printf ( "number of fields returned: %d\n" ,mysql_num_fields(result)); |
34 | //读取结果集的内容 |
35 | while (row = mysql_fetch_row(result)) { |
36 | printf ( "table: %s\n" ,(((row[0]==NULL)&&(! strlen (row[0]))) ? "NULL" : row[0]) ) ; |
37 | } |
38 | //释放结果集 |
39 | mysql_free_result(result); |
40 | //关闭数据库连接 |
41 | mysql_close(handle); |
42 | |
43 | system ( "PAUSE" ); |
44 | //为了兼容大部分的编译器加入此行 |
45 | return 0; |
46 | } |