// sqlserverTest1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include<stdio.h>
#include<windows.h>
#include<sql.h>
#include<sqlext.h>
#include<sqltypes.h>
#include<iostream>
int main()
{
SQLRETURN res;
SQLHENV renv;
SQLHDBC rdbc;
SQLHSTMT rstmt;
res = SQLAllocHandle(SQL_HANDLE_ENV, NULL, &renv);//申请环境句柄
res = SQLSetEnvAttr(renv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER); // 配置环境句柄
res = SQLAllocHandle(SQL_HANDLE_DBC, renv, &rdbc);//申请数据库连接句柄
// vs 2013 使用: SQLWCHAR*
SQLWCHAR db[] = L"first";
SQLWCHAR user[] = L"111";
SQLWCHAR password[] = L"111111";
//VS2013上,这是正确连接用法
res = SQLConnect(rdbc, db, SQL_NTS, user, SQL_NTS, password, SQL_NTS);
if (!(res == SQL_SUCCESS || res == SQL_SUCCESS_WITH_INFO))
{
printf("连接数据库失败!\n");
return -1;
}
res = SQLAllocHandle(SQL_HANDLE_STMT, rdbc, &rstmt);
SQLWCHAR sql1[] = L"insert into first.dbo.v1 (a,b,c,d,h,m) values ('a6','b6',48,45,44,'t')";
res = SQLExecDirect(rstmt, sql1, SQL_NTS);
if (res == SQL_SUCCESS || res == SQL_SUCCESS_WITH_INFO)
{
std::cout << "插入成功!";
}
else
{
std::cout << res << "\n";
std::cout << "插入失败!";
}
SQLWCHAR sql3[] = L"update first.dbo.v1 set a='ak',b='bk',c=19,d=18 where a='aa'";
res = SQLExecDirect(rstmt, sql3, SQL_NTS);
if (res == SQL_SUCCESS || res == SQL_SUCCESS_WITH_INFO)
{
std::cout << "插入成功!";
}
else
{
std::cout << res << "\n";
std::cout << "插入失败!";
}
SQLWCHAR sql2[] = L"select * from first.dbo.v1";
// ret=SQLExecDirect(hstmt,sql1,SQL_NTS);
res = SQLExecDirect(rstmt, sql2, SQL_NTS);
if (res == SQL_SUCCESS || res == SQL_SUCCESS_WITH_INFO)
{
SQLCHAR str1[20], str2[20], str3[20], str4[20];
// VC 6.0
SQLINTEGER strlen1, strlen2, strlen3, strlen4;
while (SQLFetch(rstmt) != SQL_NO_DATA)
{
SQLGetData(rstmt, 1, SQL_C_CHAR, str1, 20, &strlen1); //获取第一列数据
SQLGetData(rstmt, 2, SQL_C_CHAR, str2, 20, &strlen2);
SQLGetData(rstmt, 3, SQL_C_CHAR, str3, 50, &strlen3);
SQLGetData(rstmt, 4, SQL_C_CHAR, str4, 50, &strlen4);
printf("%s\t%s\t%s\t%s\n", str1, str2, str3, str4);
}
}
// 增加
//SQLWCHAR addsql[] = L"insert into first.dbo.v1 (a,b,c,d,h,m) values ('a4','b4',78,65,4,'n')";
SQLFreeHandle(SQL_HANDLE_DBC, rdbc);
SQLFreeHandle(SQL_HANDLE_ENV, renv);
SQLFreeHandle(SQL_HANDLE_STMT, rstmt);//释放环境句柄
return 0;
}