一、问题描述
将 Mysql 嵌入到 C++ 后,在图形界面上面难免有硬伤。为了 select, show, desc, explain 执行后返回的结果集更加好看,我决定画一个表。
在网上查找一段时间后,发现了一位博主给的比较好的代码,实现了画表的函数,但是函数的参数如何获得却没有给出。
在这里我补全了整个代码,请看代码实现。
二、代码实现
DrawTable.h
将res结果集传入构造函数,在构造函数内实现几个参数的获取。
#pragma once
#include "bits/stdc++.h"
#include "mysql.h"
class DrawTable {
public:
int columns;
int rows;
std::vector <int> max;
std::vector<std::vector<std::string>> Str;
std::vector<std::string> D;
// max:保存每一列中最长的属性的长度
// str:数据
// D:列名
public:
DrawTable(MYSQL_RES* res) {
columns = mysql_num_fields(res);
rows = mysql_num_rows(res);
MYSQL_FIELD *field_name = mysql_fetch_fields(res);
for (int i = 0; i < columns; ++i) {
max.push_back(strlen(field_name[i].name));
D.push_back(std::string(field_name[i].name));
}
MYSQL_ROW row;
while (row = mysql_fetch_row(res)) {
std::vector <std::string> tmp;
for (int i = 0; i < columns; ++i) {
if (row[i] != NULL) {
int columns_len = strlen(row[i]);
if (columns_len > 0) {
if (columns_len > max[i]) {
max[i] = columns_len;
}
tmp.push_back(std::string(row[i]));
}
else {
tmp.push_back(std::string("?"));
}
}
else {
int columns_len = strlen("NULL");
if (columns_len > 0) {
if (columns_len > max[i]) {
max[i] = columns_len;
}
tmp.push_back(std::string("NULL"));
}
}
}
Str.push_back(tmp);
}
}
//std::vector<int> max, int columns
void Draw_line();
// std::vector<int> max, std::vector<std::vector<std::string>> Str, std::vector<std::string> D, int columns, int row
void Draw_Datas();
};
DrawTable.cpp
#include "bits/stdc++.h"
#include "DrawTable.h"
void DrawTable::Draw_line() { //画行线
for (int i = 0; i < columns; i++) {
std::cout << "+-";
for (int j = 0; j <= max[i]; j++) {
std::cout << '-';
}
}
std::cout << '+' << std::endl;
}
void DrawTable::Draw_Datas() {
Draw_line();
for (int i = 0; i < D.size(); i++) {
std::cout << "| " << std::setw(max[i]) << std::setiosflags(std::ios::left) << std::setfill(' ') << D[i] << ' ';
}
std::cout << '|' << std::endl;
Draw_line();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
std::cout << "| " << std::setw(max[j]) << std::setiosflags(std::ios::left) << std::setfill(' ');
std::cout << Str[i][j] << ' ';
}
std::cout << '|' << std::endl;
}
Draw_line();
std::cout << "\n";
}
输出效果: