第一步:配置ODBC。在配置ODBC时有用户DSN、系统DSN、和文件DSN三种方法,为了稳妥起见,采用系统DSN。
DSN的名字叫LocalServer,帐号:sa,密码123456
第二步:打开VC,建一个win32 Console Application工程,名字随便都可以;
第三步:新建一个文件,文件名随便都可以;
第四步:拷贝如下代码:
#include <stdio.h>
#include <windows.h>
#include <sqlext.h>
#include <sqltypes.h>
#include <odbcss.h>
int main()
{
void sqlConnect();
sqlConnect();
getchar();
return 0;
}
void sqlConnect()
{
SQLHENV henv;
SQLHDBC hdbc;
SQLHSTMT hstmt;
SQLRETURN retcode;
UCHAR sql1[79]="select No from Student where
Name=‘jim‘";
retcode=SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&henv);
if(retcode==SQL_SUCCESS ||
retcode==SQL_SUCCESS_WITH_INFO)
{
retcode=SQLSetEnvAttr(henv,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0);
if(retcode==SQL_SUCCESS ||
retcode==SQL_SUCCESS_WITH_INFO)
{
retcode=SQLAllocHandle(SQL_HANDLE_DBC,henv,&hdbc);
if(retcode==SQL_SUCCESS
|| retcode==SQL_SUCCESS_WITH_INFO)
{
retcode=SQLConnect(hdbc,(SQLCHAR*)"LocalServer",SQL_NTS,(SQLCHAR*)"sa",SQL_NTS,(SQLCHAR*)"123456",SQL_NTS);
if(retcode==SQL_SUCCESS
|| retcode==SQL_SUCCESS_WITH_INFO)
{
retcode=SQLAllocHandle(SQL_HANDLE_STMT,hdbc,&hstmt);
if(retcode==SQL_SUCCESS
|| retcode==SQL_SUCCESS)
{
//绑定参数方式
char
a[20]="Jim";
SQLINTEGER
p=SQL_NTS;
//1.预编译
SQLPrepare(hstmt,sql1,79);//第三个参数与数组大小相同,而不是数据库列相同
//2.绑定参数值
SQLBindParameter(hstmt,1,SQL_PARAM_INPUT,SQL_C_CHAR,SQL_CHAR,200,0,&a,0,&p);
SQLExecute(hstmt);
printf("connection
is OK\n");
//SQLExecDirect(hstmt,sql1,79);
char
list[5];
SQLBindCol(hstmt,1,SQL_C_CHAR,list,5,0);
SQLFetch(hstmt);
printf("%s\n",list);
}
SQLDisconnect(hdbc);
}
SQLFreeHandle(SQL_HANDLE_DBC,hdbc);
}
}
}
}