Program Introduction: Sometimes we want to know which tables are in a database and what fields are in the table. I wrote a small program to implement this function.
Ideas:
1: connect to the database (nonsense)
2: obtain all the tables in the database and cache them.
3: for each table, execute the SQL command select * from XXX and output their header (if you can think of a better method, I hope to tell you ).
Code:
# Include <stdio. h> # include <stdlib. h> # include <string. h> # include <MySQL/MySQL. h> # define max_count 256 // when an error occurs, output the error message, close the connection, and exit the program void error_quit (const char * STR, MySQL * connection) {fprintf (stderr, "% s: % d: % s \ n", STR, mysql_errno (connection), mysql_error (connection); If (connection! = NULL) mysql_close (connection); exit (1);} int main (INT argc, char * argv []) {MySQL * my_con; mysql_res * my_res; mysql_field * my_field; mysql_row my_row; int rows, I, j, Res; char namebuf [max_count] [max_count] = {0}; int COUNT = 0; my_con = malloc (sizeof (MySQL )); // connect to the database mysql_init (my_con); my_con = mysql_real_connect (my_con, "127.0.0.1", "root", "aaaaaaa", "test", 0, null, client_found_rows); If (Null = my_con) error_quit ("connection fail", my_con); printf ("connection success \ n"); // obtain all the tables in the database. Res = mysql_query (my_con, "Show tables;"); If (res! = 0) error_quit ("select fail", my_con); my_res = mysql_store_result (my_con); If (null = my_res) error_quit ("Get result fail", my_con ); // buffer the query result while (1) {my_row = mysql_fetch_row (my_res); If (null = my_row) break; If (my_row [0] = NULL) printf ("null \ t"); else strcpy (namebuf [count ++], (char *) my_row [0]);} for (I = 0; I <count; I ++) {char tbuf [100] = {0}; snprintf (tbuf, 100, "select * from % s ", Namebuf [I]); // get the pointer res = mysql_query (my_con, tbuf) for the entire table content; If (res! = 0) error_quit ("select fail", my_con); my_res = mysql_store_result (my_con); If (null = my_res) error_quit ("Get result fail", my_con ); // obtain the number of columns in the table rows = mysql_num_fields (my_res); printf ("Name: % s count: % d \ n", namebuf [I], rows ); // obtain and output the header my_field = mysql_fetch_fields (my_res); For (j = 0; j <rows; j ++) printf ("% s,", my_field [J]. name); printf ("\ n ------------------------------------- \ n");} // release space, close connection mysql_free_result (my_res); mysql_close (my_con); free (my_con ); return 0 ;}
Running example (the red font is input ):
Qch @ linuxmint ~ /Program/tcode $ GCC ctemp. C-o ctemp-lmysqlclient
Qch @ linuxmint ~ /Program/tcode $./ctemp
Connection success
Name: class1 count: 4
ID, name, age, birthday,
-------------------------------------