如何从C ++项目连接到数据库(SQLSERVER)? [英] How to connect to a database (SQLSERVER) from a C++ project?

查看:89
本文介绍了如何从C ++项目连接到数据库(SQLSERVER)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了太多时间尝试连接到数据库,但没有用,任何想法都会非常感激。

这是一个MFC项目,问题在于字符串连接(可能)。



我尝试了什么:



我尝试了一些库和一些教程,但没有什么是明确的(我不敢相信它太复杂了)

我正在上课这个课程



I spent too much trying to connect to a database, but no use, any ideas Will greatly be appreciated.
It is an MFC project, The problem is with the String Connection (maybe).

What I have tried:

I tried some libraries and some tutorials, but nothing is clear ( i can't believe it is too complicated)
I am working on this class now

<pre>#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <sqltypes.h>
#include <sql.h>
#include <sqlext.h>
using namespace std;
#define SQL_RESULT_LEN 240
#define SQL_RETURN_CODE_LEN 1000
class Connect
{
	SQLHANDLE sqlConnHandle;
	SQLHANDLE sqlStmtHandle;
	SQLHANDLE sqlEnvHandle;
	SQLWCHAR retconstring[SQL_RETURN_CODE_LEN];
public :Connect() {
	sqlConnHandle = NULL;
	sqlStmtHandle = NULL;
	if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlEnvHandle))
		MessageBox(NULL, " connected to database\n", NULL, NULL);
	if (SQL_SUCCESS != SQLSetEnvAttr(sqlEnvHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0))
		MessageBox(NULL, " connected to database\n", NULL, NULL);
	if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, sqlEnvHandle, &sqlConnHandle))
		MessageBox(NULL, " connected to database\n", NULL, NULL);
	};
	 ~Connect() {};
	//define handles and variables

	//initializations
public: void connect()
{
	
	switch (SQLDriverConnectW(sqlConnHandle,
		NULL,
		(SQLWCHAR*)L"DRIVER={SQL Server};SERVER=TN1DEVLVTS49\\SQL2K14, 1433;UID=sa;PWD=Linedata1;DATABASE=Training_Project_DataBase;Trusted=true;",
		//DRIVER={SQL Server};SERVER=TN1DEVLVTS49\\SQL2K14, 1433;UID=sa;PWD=Linedata1;DATABASE=Training_Project_DataBase;Trusted=true;
		//Driver={SQL Server};Server=TN1DEVLVTS49\\SQL2K14;UID=sa;PWD=Linedata1;Database=Training_Project_DataBase;
		//(SQLWCHAR*)L"DRIVER={SQL Server};SERVER=localhost, 1433;DATABASE=Training_Project_DataBase;",
		SQL_NTS,
		retconstring,
		1024,
		NULL,
		SQL_DRIVER_NOPROMPT)) {
	case SQL_SUCCESS:
		MessageBox(NULL, "Successfully connected to SQL Server", NULL, NULL);

		break;
	case SQL_SUCCESS_WITH_INFO:

		MessageBox(NULL, "Successfully connected to SQL Server", NULL, NULL);
		break;
	case SQL_INVALID_HANDLE:

		MessageBox(NULL, " Could not connect to SQL Server", NULL, NULL);
	case SQL_ERROR:

		MessageBox(NULL, " Could not connect to SQL Server", NULL, NULL);
	default:
		break;
	}
};
};

推荐答案

有很多方法,你可以找到大量的教程,只需谷歌搜索。例如,请参阅:连接到SQL Server来自Visual C ++ | Tech How To [ ^ ]。
There are many ways, and you may find tons of tutorials, just Googling. See, for instance: Connect to SQL Server from Visual C++ | Tech How To's[^].


这篇关于如何从C ++项目连接到数据库(SQLSERVER)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆