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

ODBC-API(动态查询)

2013年05月15日 ⁄ 综合 ⁄ 共 1923字 ⁄ 字号 评论关闭

动态查询的例子.

其实就是多出了

预处理,和设置参数

#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;
	}
	
	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];
	char *ss = new char[256];
	char *ss1 = new char[256];
	long columnlen;

	SQLAllocStmt(hdbc, &hstmt);
//	retcode = SQLExecDirect(hstmt, (unsigned char*)"SELECT * FROM student", sizeof("SELECT * FROM student"));
	SQLPrepare(hstmt, (unsigned char*) "SELECT * FROM student WHERE ssex = ? AND sage > ? ", SQL_NTS);
	printf("请输入:\n");
	scanf("%s", ss);
	printf("请输入:\n");
	scanf("%s", ss1);
//	SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_CHAR, SQL_CHAR, 26, 0, &ss, NULL);
//	SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_C_CHAR, 256, 0, ss, 0, NULL);

	SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_CHAR, SQL_CHAR, 256, 0, ss, 256, NULL);
	SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT, SQL_CHAR, SQL_CHAR, 256, 0, ss1, 256, NULL);

	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);
	SQLExecute(hstmt);

//	retcode = SQLFetch(hstmt);

	if (retcode < 0)
	{
		cout << "没有执行语句" << endl;
	}
	SQLExecute(hstmt);
	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;
}

抱歉!评论已关闭.