#include#include SQLHENV henv; SQLHDBC hdbc; SQLHSTMT hstmt; // Connect to the database SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv); SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER*)SQL_OV_ODBC3, 0); SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); SQLConnect(hdbc, "database", SQL_NTS, "username", SQL_NTS, "password", SQL_NTS); // Prepare the SQL query SQLPrepare(hstmt, "INSERT INTO users (name, age) VALUES (?, ?)", SQL_NTS); // Bind the parameters to the query char name[20] = "John Smith"; int age = 30; SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, 20, 0, name, sizeof(name), NULL); SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT, SQL_C_LONG, SQL_INTEGER, 0, 0, &age, 0, NULL); // Execute the query SQLExecute(hstmt); // Disconnect from the database SQLDisconnect(hdbc); SQLFreeHandle(SQL_HANDLE_DBC, hdbc); SQLFreeHandle(SQL_HANDLE_ENV, henv);
#includeThis code connects to a database, prepares a SELECT query with one parameter, binds the parameter value to the query, executes it to retrieve a user record from the "users" table, and fetches the results to display the user's name and age. The PreparedStatement class is a part of the SQL Connectivity Library, which is included in popular C++ development environments such as Visual Studio, Code::Blocks, and Eclipse. It provides a convenient and secure way to interact with databases, helping developers avoid SQL injection attacks and other common pitfalls.#include SQLHENV henv; SQLHDBC hdbc; SQLHSTMT hstmt; // Connect to the database SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv); SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER*)SQL_OV_ODBC3, 0); SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); SQLConnect(hdbc, "database", SQL_NTS, "username", SQL_NTS, "password", SQL_NTS); // Prepare the SQL query SQLPrepare(hstmt, "SELECT name, age FROM users WHERE id = ?", SQL_NTS); // Bind the parameter to the query int user_id = 1; SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_LONG, SQL_INTEGER, 0, 0, &user_id, 0, NULL); // Execute the query SQLExecute(hstmt); // Fetch the results char name[20]; int age; SQLBindCol(hstmt, 1, SQL_C_CHAR, name, sizeof(name), NULL); SQLBindCol(hstmt, 2, SQL_C_LONG, &age, 0, NULL); SQLFetch(hstmt); // Show the results std::cout << "Name: " << name << ", Age: " << age << std::endl; // Disconnect from the database SQLDisconnect(hdbc); SQLFreeHandle(SQL_HANDLE_DBC, hdbc); SQLFreeHandle(SQL_HANDLE_ENV, henv);