C语言:获取某个mysql数据库中所有的表及其表中所有的字段名
2013-10-31 13:03
513 查看
程序简介:有时候我们想知道一个数据库中到底有哪些表,表中都有些什么字段。我写了一个小程序来实现这个功能。
思路:
1:连接数据库(废话)
2:获取数据库中所有的表,并将它们缓存下来。
3:对于每个表,就执行SQL命令select * from XXX,并将它们的表头输出(如果大家能想到更好的方法,望告知)。
思路:
1:连接数据库(废话)
2:获取数据库中所有的表,并将它们缓存下来。
3:对于每个表,就执行SQL命令select * from XXX,并将它们的表头输出(如果大家能想到更好的方法,望告知)。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <mysql/mysql.h> #define MAX_COUNT 256 //发生错误时,输出错误信息,关闭连接,退出程序 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) ); //连接数据库 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"); //获取整个数据库中的所有表 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); //缓冲刚才查询的结果 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]); //获取整个表的内容的指针 res = mysql_query(my_con, tbuf); 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); //获取表的列数 rows = mysql_num_fields(my_res); printf("name: %s count: %d\n", namebuf[i], rows); //获取并输出表头 my_field = mysql_fetch_fields(my_res); for(j=0; j<rows; j++) printf("%s, ", my_field[j].name); printf("\n-------------------------------------\n\n"); } //释放空间,关闭连接 mysql_free_result(my_res); mysql_close(my_con); free(my_con); return 0; }
相关文章推荐
- C语言:获取某个mysql数据库中所有的表及其表中所有的字段名
- 反射-获取类及其父类中声明的所有字段集合
- 通过Linq来获取数据库中的所有表及其字段名称
- 转载Sql 获取数据库所有表及其字段名称,类型,长度
- 获取数据库所有表及其字段名称、类型、长度
- SQL Server 2008中获取数据库所有表及其字段名称、类型、长度的SQL
- C#获取MySQL数据库中的所有的表名和字段名及字段的数据类型
- SQL Server 中获取数据库所有表及其字段名称、类型、长度的SQL
- SQL Server 2008中获取数据库所有表及其字段名称、类型、长度的SQL
- Sql :获取数据库所有表及其字段名称、类型、长度 (也可以指定单张或若干张表的详细信息。。。)
- 通过Linq来获取数据库中的所有表及其字段名称
- 获取数据库所有表及其字段名称、类型、长度
- 【原创】C# 递归获取指定目录的子目录及其所有文件
- Linux 获取所有网口及其索引
- JAVA 获取某个盘符下所有文件夹及其文件路径,并返回标准JSON字符串
- mysql 获取一张表的所有的字段
- 两种获取MySql数据库中所有表的主键和外键约束信息的Sql语句
- java 操作MySQL数据库的一个例子,包括表字段,类型,编码格式,表的所有值读取
- [置顶] 【C语言】获取一个数二进制序列中所有的偶数位和奇数位,分别输出二进制序列
- java中使用反射获取pojo(实体)类的所有字段值