How do I connect to an ODBC Database using c and do a select or insert or update.

1030071002 used Ask the Experts™
How do I connect to an ODBC Database using c and do a select, insert and update.

1. is this possible to do

2. can give me examples not links

3. please give example of  select, insert and update in c.

4 please tell me what library to include.
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
yes it is possible
you need odbc32.lib (assume you are in a windows environment)

then your code will looks like

#include <windows.h>
#include <sql.h>    
#include <sqlext.h>  

int main()
    SQLHENV env;
    SQLHDBC con;
    SQLCHAR dsn[] = "mydsn", uid[] = "myuser", pwd[] = "mypass"; // fill the values
    SQLHSTMT stmt;
    SQLCHAR col1[20], col2[20];
    SQLAllocHandle(SQL_HANDLE_ENV, NULL, &env);

    SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0);

    SQLAllocHandle(SQL_HANDLE_DBC, env, &con);

    SQLConnect(con, dsn, SQL_NTS, uid, SQL_NTS, pwd, SQL_NTS);

    SQLAllocHandle(SQL_HANDLE_STMT, con, &stmt);

    SQLExecDirect(stmt, "SELECT * FROM tbl1;", SQL_NTS);

    while (SQL_SUCCEEDED(SQLFetch(stmt)))
          SQLGetData(stmt, 1, SQL_C_CHAR, col1, sizeof(col1), NULL);
          SQLGetData(stmt, 2, SQL_C_CHAR, col2, sizeof(col2), NULL);
          printf("%s %s\n", col1, col2);
    SQLFreeHandle(SQL_HANDLE_STMT, stmt);
    SQLFreeHandle(SQL_HANDLE_DBC, con);
    SQLFreeHandle(SQL_HANDLE_ENV, env);
and for insert it would be something like :

SQLExecDirect(stmt, "insert into tbl1 (col1,col2) values('val1','val2')", SQL_NTS);
and for update :

SQLExecDirect(stmt, "update tbl1 set col1 = 'val1' ", SQL_NTS);
Acronis in Gartner 2019 MQ for datacenter backup

It is an honor to be featured in Gartner 2019 Magic Quadrant for Datacenter Backup and Recovery Solutions. Gartner’s MQ sets a high standard and earning a place on their grid is a great affirmation that Acronis is delivering on our mission to protect all data, apps, and systems.


where can I find this file on a windows machine odbc32.lib
you can download it or find it the windows SDK or Visual c++ express edition
Top Expert 2016
what compiler you were using?

if you found the sql.h in a folder with name 'include', the odbc32.lib should be in folder 'lib' at same level than folder include.

i found 4 occurrences at my current environment. they were as Michel_Nialon told part of sdk's for different compiler versions.


Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial