大佬们,请问C++使用ODBC连接数据库,显示连接正常但是执行SQL语句的时候SQLExecute返回值为SQL_NULL_DATA(-1)该怎么处理呢?
运行效果截图:
全部代码:
#include <stdio.h>
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <sqltypes.h>
#include <iostream>
#include <string>
#pragma comment(lib,"odbc32.lib")
#pragma warning(disable : 4996)
#pragma warning(disable : 6054)
using namespace std;
SQLRETURN ret;//返回信息
SQLHENV henv;//环境句柄
SQLHDBC hdbc;//连接句柄
SQLHSTMT hstmt;//语句句柄
//添加病人(姓名,性别,年龄,地址,费用)
int AddPaintent(string Patient, string Sex, int Age, string Adress, double Fee) {
cout << "申请环境句柄" << endl;
//申请环境句柄
ret = SQLAllocHandle(SQL_HANDLE_ENV, NULL, &henv);
//设置环境句柄
ret = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER);
if (ret < 0) {cout << "版本不对" << endl;}
//申请数据库连接句柄
ret = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
if (ret < 0) { cout << "链接句柄错误" << endl; }
//设置连接
ret = SQLConnect(hdbc, (SQLCHAR*)"SJXM", SQL_NTS, (SQLCHAR*)"Admin", SQL_NTS, (SQLCHAR*)"密码", SQL_NTS);
if (ret < 0) { cout << "链接错误" << endl; }
if (ret == SQL_SUCCESS || ret == SQL_SUCCESS_WITH_INFO)//链接成功
{
cout << "链接成功" << endl;
//申请SQL语句
SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
//使用指定数据库
SQLCHAR ConnectDatabaseSql[] = "use Test;";
//执行语句
SQLExecDirect(hstmt, (SQLCHAR*)ConnectDatabaseSql, SQL_NTS);
SQLCHAR SearchResult[1024];//定义SQL语句
char SQLSearch[1024];
char pa[20], se[5], ad[20];
strcpy_s(pa, Patient.c_str());
strcpy_s(se, Sex.c_str());
strcpy_s(ad, Adress.c_str());
//sprintf_s(SQLSearch, "insert into Patient (Patient, Sex, Age, Adress, Medcine Fee) values ('%s','%s','%d','%s','%lf');", pa, se, Age, ad, Fee);
sprintf_s(SQLSearch, "insert into Patient ( Age, Medcine Fee) values ('%d','%lf');", Age, Fee);//怀疑是string的错误,但是去掉那些之后也不行
strcpy((char*)SearchResult, SQLSearch);//语句赋值
//绑定语句准备执行
SQLPrepare(hstmt, (SQLCHAR*)SearchResult, SQL_NTS);
//执行语句
ret = SQLExecute(hstmt);
if (ret == SQL_SUCCESS_WITH_INFO || ret == SQL_SUCCESS)//执行成功
{
cout << "添加成功" << endl;
SQLFreeHandle(SQL_HANDLE_STMT, hstmt);//释放语句
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);//释放连接
SQLFreeHandle(SQL_HANDLE_ENV, henv);//释放环境
return 1;//添加成功
}
else
{
SQLFreeHandle(SQL_HANDLE_STMT, hstmt);//释放语句
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);//释放连接
SQLFreeHandle(SQL_HANDLE_ENV, henv);//释放环境
if (ret == SQL_NULL_DATA) {
cout << "SQL_NULL_DATA" << endl;
}
else {
cout << ret << endl;
}
return 2;//添加失败,错误:已有该成员
}
}
else {
cout << "连接失败:" << ret << endl;
return 3;//添加失败,错误:连接错误
}
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);//释放连接句柄
SQLFreeHandle(SQL_HANDLE_ENV, henv);//释放环境句柄
}
int main() {
string Patient = "蒂蒂", Sex = "女", Adress = "北京";
int Age = 18;
double Fee = 3000.01;
cout << "开始执行插入函数" << endl;
AddPaintent(Patient, Sex, Age, Adress, Fee);
return 0;
}