#include<windows.h>
#include<stdio.h>
#include <sql.h>
#include <sqlext.h>
int main()
{
SQLHENV henv;
SQLHDBC hdbc;
SQLHSTMT hstm;
SQLCHAR theDiagState[50];
SQLCHAR theMessageText[255];
SQLINTEGER theNativeState;
SQLSMALLINT iOutputNo;
SQLCHAR strcon[1024]="DRIVER={SQL Server};SERVER=192.168.0.241,1433;UID=sa;PWD=1234;";
SQLRETURN hr;
hr=SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&henv);
hr=SQLSetEnvAttr(henv,SQL_ATTR_ODBC_VERSION,(SQLPOINTER) SQL_OV_ODBC3,0);
hr=SQLAllocHandle(SQL_HANDLE_DBC,henv,&hdbc);
//第一种方法
// hr=SQLDriverConnect(hdbc,NULL,(SQLCHAR*)strcon,SQL_NTS, NULL,255,NULL,SQL_DRIVER_NOPROMPT);
//第二种方法
// hr=SQLConnect(hdbc,(SQLCHAR*)"student",SQL_NTS,(SQLCHAR*)"sa",SQL_NTS,(SQLCHAR*)"1234",SQL_NTS);
if(SQL_SUCCESS!=hr&&SQL_SUCCESS_WITH_INFO!=hr)
{
SQLGetDiagRec(SQL_HANDLE_DBC,hdbc,1,(SQLCHAR*)theDiagState,&theNativeState,(SQLCHAR*)theMessageText,100,&iOutputNo);
printf("connect error(%d) :%s/r/n", hr,theMessageText);
return 0;
}
SQLCHAR str0[]="use student";
SQLCHAR str1[]="UPDATE stu SET sname = '张大' where sno = 1006";
SQLCHAR str2[]="select * from stu";
//////////////////////////////////////////////////////////////////////////
printf("/r/nSQL中的库名:(use master select name from stu)/r/n");
//////////////////////////////////////////////////////////////////////////
hr=SQLAllocHandle(SQL_HANDLE_STMT,hdbc,&hstm);
hr=SQLExecDirect(hstm,str0,SQL_NTS);
if(SQL_SUCCESS!=hr&&SQL_SUCCESS_WITH_INFO!=hr)
{
SQLGetDiagRec(SQL_HANDLE_DBC,hstm,1,(SQLCHAR*)theDiagState,&theNativeState,(SQLCHAR*)theMessageText,100,&iOutputNo);
printf( "execute error(%d) :%s/r/n", hr,theMessageText);
return 0;
}
hr=SQLExecDirect(hstm,str1,SQL_NTS);
if(SQL_SUCCESS!=hr&&SQL_SUCCESS_WITH_INFO!=hr)
{
SQLGetDiagRec(SQL_HANDLE_DBC,hstm,1,(SQLCHAR*)theDiagState,&theNativeState,(SQLCHAR*)theMessageText,100,&iOutputNo);
printf( "execute error(%d) :%s/r/n", hr,theMessageText);
return 0;
}
hr=SQLExecDirect(hstm,(unsigned char *)"{call mytest_1}",SQL_NTS);
if(SQL_SUCCESS!=hr&&SQL_SUCCESS_WITH_INFO!=hr)
{
SQLGetDiagRec(SQL_HANDLE_DBC,hstm,1,(SQLCHAR*)theDiagState,&theNativeState,(SQLCHAR*)theMessageText,100,&iOutputNo);
printf( "execute error(%d) :%s/r/n", hr,theMessageText);
return 0;
}
//显示结果集
SQLCHAR szName[50],szSno[50];
SQLINTEGER cbName,cbSno;//用来保存得到的数据的长度
while (TRUE) {//循环得到所有行
hr = SQLFetch(hstm);//移动光标
if (hr == SQL_ERROR || hr == SQL_SUCCESS_WITH_INFO) {
printf("error SQLFetch/n");
}
if (hr == SQL_SUCCESS || hr == SQL_SUCCESS_WITH_INFO){
SQLGetData(hstm, 1, SQL_C_CHAR, szSno, 50, &cbSno);
//此处并没有指明BufferLength参数的值,是因为数据类型是定长的LONG型
SQLGetData(hstm, 2, SQL_C_CHAR, szName, 50, &cbName);
printf(" %s %s/n", szSno,szName);
}
else
{
break;
}
}
hr=SQLDisconnect(hdbc);
hr=SQLFreeHandle(SQL_HANDLE_DBC,hdbc);
hr=SQLFreeHandle(SQL_HANDLE_ENV,henv);
printf("press any key continue.../r/n");
getchar();
return 0;
}