Guides
Setting up an Application
Alternatively, you can connect to the ODBC driver using  [`SQLDriverConnect`](https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqldriverconnect-function?view=sql-server-ver16).
`SQLDriverConnect` accepts a connection string in which you can configure the database using any of the available [DuckDB configuration options](#docs:configuration:overview).  
```cpp
SQLHANDLE env;
SQLHANDLE dbc;

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);

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

SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);

SQLCHAR str[1024];
SQLSMALLINT strl;
std::string dsn = "DSN=DuckDB;allow_unsigned_extensions=true;access_mode=READ_ONLY"
SQLDriverConnect(dbc, nullptr, (SQLCHAR*)dsn.c_str(), SQL_NTS, str, sizeof(str), &strl, SQL_DRIVER_COMPLETE)

std::cout << "Connected!" << std::endl;
```  
#### 3. Adding a Query {#docs:guides:odbc:general::3-adding-a-query}  
Now that the application is set up, we can add a query to it.  First, we need to allocate a statement handle:  
```cpp
SQLHANDLE stmt;
SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
```  
Then we can execute a query:  
```cpp
SQLExecDirect(stmt, (SQLCHAR*)"SELECT * FROM integers", SQL_NTS);
```  
#### 4. Fetching Results {#docs:guides:odbc:general::4-fetching-results}  
Now that we have executed a query, we can fetch the results.  First, we need to bind the columns in the result set to buffers:  
```cpp
SQLLEN int_val;
SQLLEN null_val;
SQLBindCol(stmt, 1, SQL_C_SLONG, &int_val, 0, &null_val);
```  
Then we can fetch the results:  
```cpp
SQLFetch(stmt);
```  
#### 5. Go Wild {#docs:guides:odbc:general::5-go-wild}  
Now that we have the results, we can do whatever we want with them.  For example, we can print them:  
```cpp
std::cout << "Value: " << int_val << std::endl;
```  
or do any other processing we want.  As well as executing more queries and doing any thing else we want to do with the database such as inserting, updating, or deleting data.  
#### 6. Free the Handles and Disconnecting {#docs:guides:odbc:general::6-free-the-handles-and-disconnecting}  
Finally, we need to free the handles and disconnect from the database.  First, we need to free the statement handle:  
```cpp
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
```  
Then we need to disconnect from the database:  
```cpp
SQLDisconnect(dbc);
```  
And finally, we need to free the connection handle and the environment handle:  
```cpp
SQLFreeHandle(SQL_HANDLE_DBC, dbc);
SQLFreeHandle(SQL_HANDLE_ENV, env);
```  
Freeing the connection and environment handles can only be done after the connection to the database has been closed.  Trying to free them before disconnecting from the database will result in an error.