In this article, we are going to see, step by step, how we can connect to SQL Server from a Visual C++ program using an ODBC connection.
Prior to start reading, if you are really interested in learning Programming, then you should definitely check my 6-hour online course, “Introduction to Computer Programming for Beginners“. My course can help to easily get started with the basics of Programming, as well as with the following 6 interesting Programming/Scripting Languages: C, C++, C#, Java, Python and SQL.
Great! Let’s begin this interesting tutorial!
Creating an Empty Visual C++ Win32 Console Application
We start this journey, by first creating an empty Visual C++ Win32 Console Application in Visual Studio, by following the below steps:
Step 1: Let’s start a new project in Visual Studio:
Launching a new project in Visual Studio.
Step 2: Create a new Visual C++ – Win32 Console Application.
Creating a Win32 Console Application in Visual Studio.
Step 3: Click on the “Finish” button to start the project.
Completing the empty project creation in Visual Studio.
Including the Proper Libraries in your Visual C++ Project
Now it’s the time to include the proper libraries to your new C++ project in visual studio. Here’s how:
Step 4: Add the following code before the int main() function:
#include "stdafx.h"
//include the below additional libraries
#include <iostream>
#include <windows.h>
#include <sqlext.h>
#include <sqltypes.h>
#include <sql.h>
//use the std namespace
using namespace std;
Note that #include “stdafx.h” is automatically added by the project wizard.
Learn how you can efficiently work with SQL Server databases, via the Python Programming Language!
This helps you learn how to access and work with SQL Server databases, directly from your Python programs, by teaching you how to perform all the major database development operations from within your Python code.
(Lifetime Access, Q&A, Certificate of Completion, downloadable resources and more!)
Now, let’s implement the proper logic, by including the below code in the “main” function:
Step 5: Replace your int main() function with the below code, modify the connection string, T-SQL query, variables, etc. accordingly and then build the solution (press F6 or click on Build–Build solution).
int main() {
#define SQL_RESULT_LEN 240
#define SQL_RETURN_CODE_LEN 1000
//define handles and variables
SQLHANDLE sqlConnHandle;
SQLHANDLE sqlStmtHandle;
SQLHANDLE sqlEnvHandle;
SQLWCHAR retconstring[SQL_RETURN_CODE_LEN];
//initializations
sqlConnHandle = NULL;
sqlStmtHandle = NULL;
//allocations
if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlEnvHandle))
goto COMPLETED;
if (SQL_SUCCESS != SQLSetEnvAttr(sqlEnvHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0))
goto COMPLETED;
if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, sqlEnvHandle, &sqlConnHandle))
goto COMPLETED;
//output
cout << "Attempting connection to SQL Server...";
cout << "\n";
//connect to SQL Server
//I am using a trusted connection and port 14808
//it does not matter if you are using default or named instance
//just make sure you define the server name and the port
//You have the option to use a username/password instead of a trusted connection
//but is more secure to use a trusted connection
switch (SQLDriverConnect(sqlConnHandle,
NULL,
//(SQLWCHAR*)L"DRIVER={SQL Server};SERVER=localhost, 1433;DATABASE=master;UID=username;PWD=password;",
(SQLWCHAR*)L"DRIVER={SQL Server};SERVER=localhost, 1433;DATABASE=master;Trusted=true;",
SQL_NTS,
retconstring,
1024,
NULL,
SQL_DRIVER_NOPROMPT)) {
case SQL_SUCCESS:
cout << "Successfully connected to SQL Server";
cout << "\n";
break;
case SQL_SUCCESS_WITH_INFO:
cout << "Successfully connected to SQL Server";
cout << "\n";
break;
case SQL_INVALID_HANDLE:
cout << "Could not connect to SQL Server";
cout << "\n";
goto COMPLETED;
case SQL_ERROR:
cout << "Could not connect to SQL Server";
cout << "\n";
goto COMPLETED;
default:
break;
}
//if there is a problem connecting then exit application
if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sqlConnHandle, &sqlStmtHandle))
goto COMPLETED;
//output
cout << "\n";
cout << "Executing T-SQL query...";
cout << "\n";
//if there is a problem executing the query then exit application
//else display query result
if (SQL_SUCCESS != SQLExecDirect(sqlStmtHandle, (SQLWCHAR*)L"SELECT @@VERSION", SQL_NTS)) {
cout << "Error querying SQL Server";
cout << "\n";
goto COMPLETED;
}
else {
//declare output variable and pointer
SQLCHAR sqlVersion[SQL_RESULT_LEN];
SQLINTEGER ptrSqlVersion;
while (SQLFetch(sqlStmtHandle) == SQL_SUCCESS) {
SQLGetData(sqlStmtHandle, 1, SQL_CHAR, sqlVersion, SQL_RESULT_LEN, &ptrSqlVersion);
//display query result
cout << "\nQuery Result:\n\n";
cout << sqlVersion << endl;
}
}
//close connection and free resources
COMPLETED:
SQLFreeHandle(SQL_HANDLE_STMT, sqlStmtHandle);
SQLDisconnect(sqlConnHandle);
SQLFreeHandle(SQL_HANDLE_DBC, sqlConnHandle);
SQLFreeHandle(SQL_HANDLE_ENV, sqlEnvHandle);
//pause the console window - exit when key is pressed
cout << "\nPress any key to exit...";
getchar();
}
About the Connection Strings
As you can see, in the above code, I have specified the connection string as below:
With the above connection string, I’m attempting a trusted connection to SQL Server on localhost, port 1433. Also, note that by the time I am using SQLWCHAR I need to insert an L prior to the connection string value.
Furthermore, note that it doesn’t matter if you are trying to connect to a default or named instance of SQL Server. Just make sure you define the server name and the port number.
Also, if you want to connect to SQL Server using a username/password instead of a trusted connection, you can use a connection string like the below:
This was a simple example on how you can connect to SQL Server from Visual C++ and run a simple query.
You can easily modify this code in order to suit your needs.
If you want to see an example of retrieving more than one column using queries against SQL Server, you can find more information in this MS Docs article.
Learn Programming From Scratch – Enroll to our Online Course!
Artemakis Artemiou is a seasoned Senior Database and AI/Automation Architect with over 20 years of expertise in the IT industry. As a Certified Database, Cloud, and AI professional, he has been recognized as a thought leader, earning the prestigious Microsoft Data Platform MVP title for nine consecutive years (2009-2018). Driven by a passion for simplifying complex topics, Artemakis shares his expertise through articles, online courses, and speaking engagements. He empowers professionals around the globe to excel in Databases, Cloud, AI, Automation, and Software Development. Committed to innovation and education, Artemakis strives to make technology accessible and impactful for everyone.
Views:21,019
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent. Read More
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
Cookie
Duration
Description
cookielawinfo-checkbox-analytics
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional
11 months
The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy
11 months
The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.