一、结果展示
如果你想得到类似这样的数据,接下来的代码或许有所帮助
二、代码分享
#include<windows.h>
#include<iostream>
#include <assert.h>
#include<sql.h>
#include <sqlext.h>
using namespace std;
int main() {
SQLHENV serverhenv;
SQLHDBC serverhdbc;
SQLHSTMT serverhstmt;
SQLRETURN ret;
SQLCHAR cno[20] = { 0 }, cname[20] = { 0 }, semester[10] = { 10 };
//SQLINTEGER grade = 0, length;
SQLLEN grade = 0, length;
//分配环境句柄
ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &serverhenv);
//设置环境属性
ret = SQLSetEnvAttr(serverhenv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
if (!SQL_SUCCEEDED(ret)) {
cout << "AllocEnvHandle error!" << endl;
system("pause");
}
//分配连接句柄
ret = SQLAllocHandle(SQL_HANDLE_DBC, serverhenv, &serverhdbc);
if (!SQL_SUCCEEDED(ret)) {
cout << "AllocDbcHandle error!" << endl;
system("pause");
}
//数据库连接
//ret = SQLConnect(serverhdbc, (SQLCHAR*)"odbc_test(数据源名称)", SQL_NTS, (SQLCHAR*)"root(数据库用户名)", SQL_NTS, (SQLCHAR*)"123456(数据库用户密码)", SQL_NTS);
ret = SQLConnect(serverhdbc, (SQLCHAR*)"vsodbc07", SQL_NTS, (SQLCHAR*)"root", SQL_NTS, (SQLCHAR*)"root", SQL_NTS);//连接数据库
if (!SQL_SUCCEEDED(ret)) {
cout << "SQL_Connect error!" << endl;
system("pause");
}
//分配执行语句句柄
ret = SQLAllocHandle(SQL_HANDLE_STMT, serverhdbc, &serverhstmt);
//执行SQL语句
//ret = SQLExecDirect(serverhstmt, (SQLCHAR*)"insert into course values('C01','数据库','春',NULL);", SQL_NTS);//插入数据
//ret = SQLExecDirect(serverhstmt, (SQLCHAR*)"update course set semester='秋' where cno='C01';", SQL_NTS);//修改数据
//ret = SQLExecDirect(serverhstmt, (SQLCHAR*)"delete from course where cno='C01';", SQL_NTS);//删除数据
ret = SQLExecDirect(serverhstmt, (SQLCHAR*)"select * from course;", SQL_NTS);
if (ret == SQL_SUCCESS || ret == SQL_SUCCESS_WITH_INFO){
//绑定数据
SQLBindCol(serverhstmt, 1, SQL_C_CHAR, (void*)cno, sizeof(cno), &length);
SQLBindCol(serverhstmt, 2, SQL_C_CHAR, (void*)cname, sizeof(cname), &length);
SQLBindCol(serverhstmt, 3, SQL_C_CHAR, (void*)semester, sizeof(semester), &length);
//将光标移动到下行,即获得下行数据
//while (SQL_NO_DATA != SQLFetch(serverhstmt)) {
for (int i = 0;i<3; i++) {
if(SQL_NO_DATA != SQLFetch(serverhstmt)){
cout << "cno:" << cno << " cname:" << cname << " semester:" << semester;
cout << "55"<< endl;
}
}
}
//释放语句句柄
ret = SQLFreeHandle(SQL_HANDLE_STMT, serverhstmt);
if (SQL_SUCCESS != ret && SQL_SUCCESS_WITH_INFO != ret)
cout << "free hstmt error!" << endl;
//断开数据库连接
ret = SQLDisconnect(serverhdbc);
if (SQL_SUCCESS != ret && SQL_SUCCESS_WITH_INFO != ret)
cout << "disconnected error!" << endl;
//释放连接句柄
ret = SQLFreeHandle(SQL_HANDLE_DBC, serverhdbc);
if (SQL_SUCCESS != ret && SQL_SUCCESS_WITH_INFO != ret)
cout << "free hdbc error!" << endl;
//释放环境句柄句柄
ret = SQLFreeHandle(SQL_HANDLE_ENV, serverhenv);
if (SQL_SUCCESS != ret && SQL_SUCCESS_WITH_INFO != ret)
cout << "free henv error!" << endl;
system("pause");
}
这两篇博客都是关于VS通过ODBC连接MYSQL
下一篇将分享VS直接连接MYSQL
欢迎交流探讨~