| 1 | #include <stdio.h> |
| 2 | #include <stdlib.h> |
| 3 | #include <mysql/mysql.h> |
| 4 | |
| 5 | //il faut : libmysqlclient-dev |
| 6 | |
| 7 | //compilation : |
| 8 | // gcc testsqlc.c -o testsqlc -I/usr/include/mysql -lmysqlclient -L/usr/lib64/mysql |
| 9 | |
| 10 | //execution : |
| 11 | //./testsqlc |
| 12 | |
| 13 | int main(void) |
| 14 | { |
| 15 | MYSQL *conn; |
| 16 | MYSQL_RES *res; |
| 17 | MYSQL_ROW row; |
| 18 | MYSQL_RES *result; |
| 19 | |
| 20 | char *server = ""; |
| 21 | char *user = ""; |
| 22 | char *password = ""; |
| 23 | char *database = ""; |
| 24 | |
| 25 | conn = mysql_init(NULL); |
| 26 | |
| 27 | /* Connect to database */ |
| 28 | if (!mysql_real_connect(conn, server, |
| 29 | user, password, database, 0, NULL, 0)) { |
| 30 | fprintf(stderr, "%s\n", mysql_error(conn)); |
| 31 | exit(1); |
| 32 | } |
| 33 | |
| 34 | /* send SQL query */ |
| 35 | if (mysql_query(conn, "show tables")) { |
| 36 | fprintf(stderr, "%s\n", mysql_error(conn)); |
| 37 | exit(1); |
| 38 | } |
| 39 | |
| 40 | res = mysql_use_result(conn); |
| 41 | |
| 42 | /* output table name */ |
| 43 | printf("MySQL Tables in mysql database:\n"); |
| 44 | while ((row = mysql_fetch_row(res)) != NULL) |
| 45 | printf("%s \n", row[0]); |
| 46 | |
| 47 | /* query */ |
| 48 | if (mysql_query(conn, "SELECT * FROM Usine")) { |
| 49 | fprintf(stderr, "%s\n", mysql_error(conn)); |
| 50 | exit(1); |
| 51 | } |
| 52 | |
| 53 | result = mysql_store_result(conn); |
| 54 | |
| 55 | if (result == NULL) { |
| 56 | fprintf(stderr, "%s\n", mysql_error(conn)); |
| 57 | exit(1); |
| 58 | } |
| 59 | |
| 60 | int num_fields = mysql_num_fields(result); |
| 61 | int i; |
| 62 | |
| 63 | printf("\nTable Usine :\n"); |
| 64 | printf("NU\tNomU\tVille\n"); |
| 65 | |
| 66 | while ((row = mysql_fetch_row(result))) { |
| 67 | for (i = 0; i < num_fields; i++) { |
| 68 | printf("%s\t", row[i] ? row[i] : "NULL"); |
| 69 | } |
| 70 | printf("\n"); |
| 71 | } |
| 72 | |
| 73 | /* close connection */ |
| 74 | mysql_free_result(res); |
| 75 | mysql_close(conn); |
| 76 | |
| 77 | return 0; |
| 78 | } |