利用ODBC数据源连接数据库实现基础查询

来源:互联网 发布:淘宝网珊瑚绒床单 编辑:程序博客网 时间:2024/06/07 02:02
#include<windows.h>#include<stdio.h>#include<stdlib.h>#include<string>#include<iostream>#include "sql.h"#include "sqltypes.h"#include "sqlext.h"using namespace std;RETCODE retcode;  //结果返回集SQLHDBC hdbc;  //定义连接句柄void print();int main(){SQLHANDLE henv;  //定义环境句柄unsigned char server[] = "NetMusicShop";   //数据源名称unsigned char username[] = "sa";  //用户名unsigned char password[] = "";  //密码//连接数据库retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);//分配ODBC环境retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);  //设置环境属性retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);  //分配连接句柄retcode = SQLConnect(hdbc, server, SQL_NTS, username, SQL_NTS,password, SQL_NTS);  //连接if(!(retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)){printf("数据库连接失败!");}else{print();}SQLFreeConnect(hdbc);  //释放连接句柄SQLFreeEnv(henv);  //释放ODBC环境句柄printf("操作已完成!\n");system("pause");return 0;}void print(){unsigned char yuju[] = "select* from Users";SQLHSTMT hstmt;  //定义语句句柄int i =1;char L1[20], L2[20], L3[20], L4[20], L5[20];long lenOut1, lenOut2, lenOut3, lenOut4, lenOut5;retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);if (retcode == SQL_SUCCESS){retcode = SQLExecDirect(hstmt, yuju, SQL_NTS);if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO){retcode = SQLBindCol(hstmt, 1, SQL_C_CHAR, L1, sizeof(L1), &lenOut1);retcode = SQLBindCol(hstmt, 2, SQL_C_CHAR, L2, sizeof(L2), &lenOut2);retcode = SQLBindCol(hstmt, 3, SQL_C_CHAR, L3, sizeof(L3), &lenOut3);retcode = SQLBindCol(hstmt, 4, SQL_C_CHAR, L4, sizeof(L4), &lenOut4);retcode = SQLBindCol(hstmt, 5, SQL_C_CHAR, L5, sizeof(L5), &lenOut5);  //把所有捆绑过的数据字段的数据拷贝到相应的缓冲区retcode = SQLFetch(hstmt);  //该函数用于将记录集的下一行变成当前行,并把所有捆绑过的数据字段的数据拷贝到相应的缓冲区while (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO){printf("%d\t%s\t%s\t%s\t%s\t%s\n", i, L1, L2,L3,L4,L5);retcode = SQLFetch(hstmt);i++;}}}SQLFreeStmt(hstmt, SQL_DROP);}
0 0