本文介绍了使用ODBC连接到SQL SERVER 2008的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在一个W32机器试图与一个数据库连接。为此,我尝试开始测试示例程序:
I'm on a W32 machine trying to get a connection with a DB. For that purpose, I tried starting testing an example program:
#include <iostream>
#include <windows.h>
#include <sqltypes.h>
#include <sql.h>
#include <sqlext.h>
using namespace std;
void show_error(unsigned int handletype, const SQLHANDLE& handle){
SQLCHAR sqlstate[1024];
SQLCHAR message[1024];
if(SQL_SUCCESS == SQLGetDiagRec(handletype, handle, 1, sqlstate, NULL, message, 1024, NULL))
cout<<"Message: "<<message<<"\nSQLSTATE: "<<sqlstate<<endl;
}
int main(){
SQLHANDLE sqlenvhandle;
SQLHANDLE sqlconnectionhandle;
SQLHANDLE sqlstatementhandle;
SQLRETURN retcode;
if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlenvhandle))
goto FINISHED;
if(SQL_SUCCESS!=SQLSetEnvAttr(sqlenvhandle,SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0))
goto FINISHED;
if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_DBC, sqlenvhandle, &sqlconnectionhandle))
goto FINISHED;
SQLCHAR retconstring[1024];
switch(SQLDriverConnect (sqlconnectionhandle,
NULL,
(SQLCHAR*)"DRIVER={SQL Server};SERVER=localhost, 1433;DATABASE=MyDatabase;UID=sa;PWD=Admin-123;",
SQL_NTS,
retconstring,
1024,
NULL,
SQL_DRIVER_NOPROMPT)){
case SQL_SUCCESS_WITH_INFO:
show_error(SQL_HANDLE_DBC, sqlconnectionhandle);
break;
case SQL_INVALID_HANDLE:
case SQL_ERROR:
show_error(SQL_HANDLE_DBC, sqlconnectionhandle);
goto FINISHED;
default:
break;
}
if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_STMT, sqlconnectionhandle, &sqlstatementhandle))
goto FINISHED;
if(SQL_SUCCESS!=SQLExecDirect(sqlstatementhandle, (SQLCHAR*)"select * from testtable", SQL_NTS)){
show_error(SQL_HANDLE_STMT, sqlstatementhandle);
goto FINISHED;
}
else{
char name[64];
char address[64];
int id;
while(SQLFetch(sqlstatementhandle)==SQL_SUCCESS){
SQLGetData(sqlstatementhandle, 1, SQL_C_ULONG, &id, 0, NULL);
SQLGetData(sqlstatementhandle, 2, SQL_C_CHAR, name, 64, NULL);
SQLGetData(sqlstatementhandle, 3, SQL_C_CHAR, address, 64, NULL);
cout<<id<<" "<<name<<" "<<address<<endl;
}
}
FINISHED:
SQLFreeHandle(SQL_HANDLE_STMT, sqlstatementhandle );
SQLDisconnect(sqlconnectionhandle);
SQLFreeHandle(SQL_HANDLE_DBC, sqlconnectionhandle);
SQLFreeHandle(SQL_HANDLE_ENV, sqlenvhandle);
}
问题是我在编译时遇到了很多问题,关于未声明的类型,例如:
The problem is that I get MANY problems when trying to compile, regarding undeclared types, for example:
'SQLHANDLE' has not been declared
'SQLHDESC' was not declared in this scope
我已链接到 libodbccpp32.a
和 libodbc32.a
库。
推荐答案
我发现stdafx.h头文件包含的顺序应该改为:
I have found with stdafx.h header that the include order should be instead:
#include <iostream>
#include <windows.h>
#include <sqlext.h>
#include <sqltypes.h>
#include <sql.h>
这篇关于使用ODBC连接到SQL SERVER 2008的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!