// マルチバイト文字セット
#include <Windows.h>
#include <sqlext.h>
#include <stdio.h>
void ErrMsg(SQLSMALLINT HandleType, SQLHANDLE Handle);
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf_s(stderr, "usage: groupby event.csv\n");
return 1;
}
// データベースへの接続
SQLHENV henv; // 環境
SQLHDBC hdbc; // 接続
SQLRETURN rc; // retcode
rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
rc = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);
rc = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
rc = SQLDriverConnect(hdbc, NULL,
(SQLTCHAR *)"driver={Microsoft Text Driver (*.txt; *.csv)}",
SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT);
if (!SQL_SUCCEEDED(rc)) {
return 1;
}
// 検索
SQLHSTMT hstmt; // 命令
rc = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
TCHAR stmt[256];
sprintf_s(stmt,
"select 艦種, 艦名, count from 艦種.csv c, ("
"select 表示順, 艦名, count(*) as count from %s a, 艦種.csv b "
"where a.艦種略号 = b.艦種略号 group by 表示順, 艦名) d "
"where c.表示順 = d.表示順 order by c.表示順, count desc", argv[1]);
rc = SQLExecDirect(hstmt, (SQLTCHAR *)stmt, SQL_NTS);
if (!SQL_SUCCEEDED(rc)) {
ErrMsg(SQL_HANDLE_STMT, hstmt);
return 1;
}
SQLSMALLINT col;
SQLTCHAR buf[256];
rc = SQLNumResultCols(hstmt, &col);
for (SQLSMALLINT i = 1; i <= col; i++) {
SQLSMALLINT datatype;
rc = SQLDescribeCol(hstmt, i, buf, _countof(buf), NULL, &datatype, NULL, NULL, NULL);
printf_s("%d: %s %d\n", i, buf, datatype);
// 4 SQL_INTEGER
// 12 SQL_VARCHAR Text
// -6 SQL_TINYINT Byte
}
TCHAR save[16] = ""; // 艦種
int c = 0;
while (TRUE) {
rc = SQLFetch(hstmt);
if (rc == SQL_NO_DATA) break;
if (rc == SQL_ERROR) break;
TCHAR type[16]; // 艦種
SQLTCHAR name[16]; // 艦名
SQLINTEGER count; // カウント
SQLLEN len;
rc = SQLGetData(hstmt, 1, SQL_C_TCHAR, type, _countof(type), &len);
rc = SQLGetData(hstmt, 2, SQL_C_TCHAR, name, _countof(name), &len);
rc = SQLGetData(hstmt, 3, SQL_C_SLONG, &count, 0, &len);
if (strcmp(save, type)) {
printf_s("\n%s:", type);
strcpy_s(save, type);
}
if (count == 1) {
printf_s(" %s", name);
} else {
printf_s(" %sx%d", name, count);
}
c += count;
}
printf_s("\ncount=%d\n", c);
rc = SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
// 終了処理
rc = SQLDisconnect(hdbc);
rc = SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
rc = SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 0;
}
void ErrMsg(SQLSMALLINT HandleType, SQLHANDLE Handle)
{
SQLTCHAR SQLState[5+1];
SQLINTEGER NativeError;
SQLTCHAR MessageText[256];
SQLSMALLINT TextLength;
SQLGetDiagRec(HandleType, Handle, 1, SQLState, &NativeError, MessageText, _countof(MessageText), &TextLength);
fprintf_s(stderr, "%s\n", MessageText);
}