Đây là phần đầu tiên của chuỗi bài viết hướng dẫn kết nối cơ sở dữ liệu SQL Server bằng ngôn ngữ C++. Những nội dung trong bài viết đều là do mình tự tìm hiểu, mò mẫm vì thế khó tránh khỏi sai sót, code không chuẩn,…

Bên dưới là code kết nối cơ sở dữ liệu, trong phần tiếp theo mình sẽ xây dựng 1 class thực hiện chức năng kết nối, truy vấn và lấy dữ liệu từ trong SQL Server.

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

using namespace std;

#define SQL_RESULT_LEN 240
#define SQL_RETURN_CODE_LEN 1000

int main() {
	SQLHANDLE sqlConnHandle;
	SQLHANDLE sqlStmtHandle;
	SQLHANDLE sqlEnvHandle;
	SQLWCHAR retconstring[SQL_RETURN_CODE_LEN];
	bool status = true;

	sqlConnHandle = NULL;
	sqlStmtHandle = NULL;

	if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlEnvHandle))
		status = false;
	if (SQL_SUCCESS != SQLSetEnvAttr(sqlEnvHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0))
		status = false;
	if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, sqlEnvHandle, &sqlConnHandle))
		status = false;

	if (status) {
		cout << "Attempting connection to SQL Server...";
		cout << "\n";

		SQLWCHAR* connectionString = (SQLWCHAR*)L"DRIVER={SQL Server};SERVER=localhost,1433;DATABASE=CuaHangSach;UID=sa;PWD=123456;Trusted=true";
		int SQLDConn = SQLDriverConnect(sqlConnHandle, NULL, connectionString, SQL_NTS, retconstring, 1024, NULL, SQL_DRIVER_NOPROMPT);

		switch (SQLDConn) {
		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";
			status = false;
			break;
		case SQL_ERROR:
			cout << "Could not connect to SQL Server";
			cout << "\n";
			status = false;
			break;
		default:
			break;
		}

		if (status == true && SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sqlConnHandle, &sqlStmtHandle))
			status = false;

		if (status) {
			cout << "\n";
			cout << "Executing T-SQL query...";
			cout << "\n";
		}
		if (status) {
			if (SQL_SUCCESS != SQLExecDirect(sqlStmtHandle, (SQLWCHAR*)L"SELECT @@VERSION", SQL_NTS)) {
				cout << "Error querying SQL Server";
				cout << "\n";
				status = false;
			}
			else {
				SQLCHAR sqlVersion[SQL_RESULT_LEN];
				SQLINTEGER ptrSqlVersion;
				while (SQLFetch(sqlStmtHandle) == SQL_SUCCESS) {
					SQLGetData(sqlStmtHandle, 1, SQL_CHAR, sqlVersion, SQL_RESULT_LEN, &ptrSqlVersion);
					cout << "\nQuery Result:\n\n";
					cout << sqlVersion << endl;
				}
			}
		}
	}

	SQLFreeHandle(SQL_HANDLE_STMT, sqlStmtHandle);
	SQLDisconnect(sqlConnHandle);
	SQLFreeHandle(SQL_HANDLE_DBC, sqlConnHandle);
	SQLFreeHandle(SQL_HANDLE_ENV, sqlEnvHandle);

	return 0;
}

Để có thể kết nối thành công SQL Server thì cần thay đổi lại thông tin cấu hình cho đúng tại dòng code này:

SQLWCHAR* connectionString = (SQLWCHAR*)L"DRIVER={SQL Server};SERVER=localhost,1433;DATABASE=CuaHangSach;UID=sa;PWD=123456;Trusted=true";
  • DRIVER={SQL Server};
  • SERVER=localhost,1433; => Tên máy chủ, port của SQL Server
  • DATABASE=CuaHangSach; => Tên database
  • UID=sa; => Tên người dùng đăng nhập SQL Server
  • PWD=123456; => Mật khẩu đăng nhập SQL Server
  • Trusted=true

Chương trình chạy thành công sẽ hiện lên kết quả như thế này.

Trong các phần tiếp theo của chuỗi bài viết “Kết nối cơ sở dữ liệu SQL Server” mình sẽ trình bày cụ thể hơn.

Được phân loại: