How to access MS SQL server by ODBC with C/C++ on linux
For ODBC setting on linux, please refer to my https://steemit.com/cn/@alanzheng/php-steemsql
The demo C code is here, for example file name is queryInfo.c:
#include <stdio.h>
#include <sql.h>
#include <sqlext.h>
void main( int argc, char** argv ) {
SQLHENV env;
SQLHDBC dbc;
SQLHSTMT stmt;
SQLRETURN ret; /* ODBC API return status */
SQLSMALLINT columns; /* number of columns in result-set */
int row = 0;
char sql[1024] = "";
/* Allocate an environment handle */
SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
/* We want ODBC 3 support */
SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
/* Allocate a connection handle */
SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);
/* Connect to the DSN mydsn */
/* You will need to change mydsn to one you have created and tested */
SQLDriverConnect(dbc, NULL, "DSN=steemDB;Uid=steemit;Pwd=steemit", SQL_NTS,
NULL, 0, NULL, SQL_DRIVER_COMPLETE);
/* Allocate a statement handle */
SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
/* execute a query */
if( argc > 1 )
sprintf(sql, "select voting_power from Accounts where name='%s'", argv[1]);
else
{
printf("No username given\n");
return;
}
SQLExecDirect(stmt, sql, SQL_NTS);
/* How many columns are there */
SQLNumResultCols(stmt, &columns);
/* Loop through the rows in the result-set */
while (SQL_SUCCEEDED(ret = SQLFetch(stmt))) {
SQLUSMALLINT i;
printf("Row %d\n", row++);
/* Loop through the columns */
for (i = 1; i <= columns; i++) {
SQLINTEGER indicator;
char buf[512];
/* retrieve column data as a string */
ret = SQLGetData(stmt, i, SQL_C_CHAR,
buf, sizeof(buf), &indicator);
if (SQL_SUCCEEDED(ret)) {
/* Handle null columns */
if (indicator == SQL_NULL_DATA) sprintf(buf, "%s", "NULL");
printf(" Column %u : %s\n", i, buf);
}
}
}
}
Then gcc compile it: gcc queryInfo.c -o queryInfo -lodbc
To run it: ./queryInfo alanzheng
Now I got my voting_power is 9077