我正在使用 ODBC 构建一个小型 SQL 客户端,能够在 SQL Server 上执行基本查询。但是,当我打印查询返回的结果时,我的列和行间隔不均匀。
例如,当我执行
EXEC sp_helprotect 'xp_dirtree';
时,我的结果如下所示:
Owner Object Grantee Grantor ProtectType Action Column
sys xp_dirtree public dbo Grant Execute
列遍布各处,通常很难辨别哪一列的数据属于哪一列。
我目前正在使用选项卡来打印每列及其数据,我知道这是问题所在。但是,有没有更好的方法来解决这个问题并根据每列的宽度均匀打印结果?如何根据每一列的宽度来间隔它,然后打印集合中的下一列?
我目前处理事情的方式是使用选项卡
\t
。
// Get total count of columns from result set
SQLUSMALLINT cCount;
SQLNumResultCols(hStmt, &cCount);
// Describe each column
SQLCHAR cName[128] = { '\0' };
SQLUSMALLINT cColumn;
for (cColumn = 1; cColumn <= cCount; cColumn++) {
SQLDescribeColA(hStmt, cColumn, cName, sizeof(cName), NULL, NULL, NULL, NULL, NULL);
printf("%s\t", cName);
}
// Fetch and print rows
SQLCHAR rResults[8192] = { '\0' };
SQLRETURN rRet = SQLFetch(hStmt);
while (rRet != SQL_NO_DATA && rRet != SQL_ERROR) {
printf("\n"); // New line for row information
for (cColumn = 1; cColumn <= cCount; cColumn++) {
SQLGetData(hStmt, cColumn, SQL_C_CHAR, rResults, sizeof(rResults), NULL);
printf("%s\t", rResults);
// Empty array for next row
memset(rResults, '\0', sizeof(rResults));
}
rRet = SQLFetch(hStmt);
}
您可以使用字段宽度说明符,例如
%10s
(或 %-10s
,具体取决于您的需要)。
如果列都应具有不同的宽度,则使用具有宽度的数组并使用
%*s
格式:
printf("%*s", widths[cColumn], rResults);