前步骤:在数据源(ODBC)进行数据源配置添加,需要有mysql-connector-odbc驱动(百度搜索下载相应位数版本)。
进行数据库开发需要:
#include
#include
#include
添加链接库:
odbc32.lib odbccp32.lib
宏定义:
#define LOGIN_TIMEOUT 30
#define MAXBUFLEN 255
#define CHECKDBSTMTERR0R(hwnd, result, hstmt) if(SQL_ERROR==result){ShowDBStmtError(hwnd,hstmt);return;}
数据库连接错误代码:
void ShowDBError(HWND hwnd,SQLSMALLINT type,SQLHANDLE sqlHandle)
{
char pStatus[10], pMsg[101];
SQLSMALLINT SQLmsglen;
char error[200] = {0};
SQLINTEGER SQLerr;
long erg2 = SQLGetDiagRec(type, sqlHandle, 1,
(SQLCHAR *)pStatus,&SQLerr,(SQLCHAR *)pMsg,100,&SQLmsglen);
wsprintf(error,"%s (%d)\n",pMsg,(int)SQLerr);
MessageBox(hwnd, error, TEXT("数据库执行错误"),MB_OK|MB_ICONERROR);
}
void ShowDBConnError(HWND hwnd,SQLHDBC hdbc)
{
ShowDBError(hwnd, SQL_HANDLE_DBC, hdbc);
}
void ShowDBStmtError(HWND hwnd,SQLHSTMT hstmt)
{
ShowDBError(hwnd, SQL_HANDLE_STMT,hstmt);
}
连接操作数据库:
void DBTest(HWND hwnd)
{
SQLHENV henv = NULL;
SQLHDBC hdbc = NULL;
SQLHSTMT hstmt = NULL;
SQLRETURN result;
SQLCHAR ConnStrIn[MAXBUFLEN]="DRIVER={MySQL ODBC 5.3 Driver};SERVER=127.0.0.1;UID=root;PWD=root;DATABASE=contacts;CharSet=gbk;";//数据库连接字符串,根据自己的实际情况填
SQLCHAR ConnStrOut[MAXBUFLEN];
//分配环境句柄
result = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
//设置管理环境属性
result = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0);
//分配连接句柄
result = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
//设置连接属性
result = SQLSetConnectAttr(hdbc, SQL_LOGIN_TIMEOUT, (void *)LOGIN_TIMEOUT, 0);
//连接数据库
result = SQLDriverConnect(hdbc, NULL,
ConnStrIn, SQL_NTS,
ConnStrOut, MAXBUFLEN,
(SQLSMALLINT *)0, SQL_DRIVER_NOPROMPT);
if (SQL_ERROR == result)
{
ShowDBConnError(hwnd, hdbc);
return;
}
//初始化语句句柄
result = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
result = SQLPrepare(hstmt, (SQLCHAR *)"insert into contact(NAME,address) valuse('哈哈', '重庆')",SQL_NTS);//创建SQL操作语句
CHECKDBSTMTERR0R(hwnd, result, hstmt);
result = SQLExecute(hstmt);//执行SQL语句
CHECKDBSTMTERR0R(hwnd, result, hstmt);
SQLFreeStmt(hstmt, SQL_CLOSE);
SQLDisconnect(hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
SQLFreeHandle(SQL_HANDLE_ENV, henv);
MessageBox(hwnd, TEXT("执行成功"),TEXT("标题"),MB_OK);
}