现在的位置: 首页 > 综合 > 正文

C++通过ODBC连接数据库

2013年06月19日 ⁄ 综合 ⁄ 共 1436字 ⁄ 字号 评论关闭

有很多种连接数据库的方法,得一种一中的钻研学习,

这里,我用的是一种比较基本的比较老的数据库连接方法,就是通过微软给提供的ODBC SQLAPI库来连接

具体的原理,我就不在这掉书袋了,大家都大体清楚,深层的就没有研究过。


先贴出直接查询的代码:

#include <windows.h>
#include <stdio.h>
#include <sql.h>
#include <stdlib.h>
#include <sqlext.h>
#include <string.h>
#include <iostream>
/*
 *一般情况下,如果返回的错误码retcode < 0,就说明没有处理得当,就是错误的
 */

using namespace std;

int main()
{
	HENV henv;
	HDBC hdbc;
	HSTMT hstmt;
	RETCODE retcode;

	SQLAllocEnv(&henv);
	SQLAllocConnect(henv, &hdbc);

	retcode = SQLConnect(hdbc,(unsigned char *)"myDB", SQL_NTS, NULL, 0, NULL, 0);
	
//	cout << retcode << endl;

	if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
	{
		cout << "连接成功" << endl;
	}
	else
	{
		cout << "连接失败" << endl;
	}
	
	retcode = SQLAllocStmt(hdbc, &hstmt);
	retcode = SQLExecDirect(hstmt, (unsigned char*)"SELECT * FROM student", SQL_NTS);
	
	char *sno = new char[256];
	char *sname = new char[256];
	char *ssex = new char[256];
	char *sage = new char[256];
	char *sdept = new char[256];

	long columnlen;

	SQLBindCol(hstmt, 1, SQL_CHAR, sno, 256, &columnlen);//这个语句可不能写错,里面的256,代表的是字符串的最大长度.
	SQLBindCol(hstmt, 2, SQL_CHAR, sname, 256, &columnlen);
	SQLBindCol(hstmt, 3, SQL_CHAR, ssex, 256, &columnlen);
	SQLBindCol(hstmt, 4, SQL_CHAR, sage, 256, &columnlen);
	SQLBindCol(hstmt, 5, SQL_CHAR, sdept, 256, &columnlen);
	
	if (retcode < 0)
	{
		cout << "没有执行语句" << endl;
	}
	retcode = SQLFetch(hstmt);

	while (retcode == SQL_ROW_SUCCESS || retcode == SQL_ROW_SUCCESS_WITH_INFO)
	{
		if (retcode == SQL_ROW_SUCCESS || retcode == SQL_ROW_SUCCESS_WITH_INFO)
		{
			printf("%s\t%s\t%s\t%s\t%s\n", sno, sname, ssex, sage, sdept);
			retcode = SQLFetch(hstmt);
		}
	}
	SQLFreeConnect(hdbc);
	SQLFreeEnv(henv); 
	return 0;
}

抱歉!评论已关闭.