前言
因为C++工程有用Sql Server数据库的计划,为了后期能方便调用Sql Server Api。我接到任务,将Sql Server api整理成库。原以为是一个简单的需求,后面还是遇到了很多问题。
前期准备
1、自己写还是有点麻烦,这里选用otl第三方库,其实就一个otlv4.h头文件。
2、安装Sql Server数据库。
3、安装Microsoft SQL Server Management Studio数据库管理工具。
4、安装visual studio 2013。(用来编写C++测试用例)
写测试用例
1、连接到数据库
#include <iostream>
using namespace std;
#include <stdio.h>
#define OTL_ODBC_MSSQL_2008 // Compile OTL 4/ODBC, MS SQL 2008
//#define OTL_ODBC // Compile OTL 4/ODBC. Uncomment this when used with MS SQL 7.0/ 2000
#define OTL_UNICODE // Enable Unicode OTL for ODBC
#define OTL_STREAM_WITH_STD_UNICODE_CHAR_ARRAY_ON
#define OTL_CPP_14_ON
#include "otlv4.h" // include the OTL 4.0 header file
otl_connect db; // connect object
int main() {
// 错误写法
// char* constr = "Driver={sql server};server=远程主机ip地址;uid=用户名;pwd=登录密码;database=链接数据库名;";
// 正确实现
char* constr = "Driver={sql server};server=远程主机ip地址,1433;uid=用户名;pwd=登录密码;database=链接数据库名;";
otl_connect::otl_initialize(); // initialize the database API environment
try{
db.rlogon(constr); // connect to the database
}
catch (otl_exception& p){ // intercept OTL exceptions
cerr << p.msg << endl; // print out error message
cerr << p.stm_text << endl; // print out SQL that caused the error
cerr << p.var_info << endl; // print out the variable that caused the error
}
db.logoff(); // disconnect from the database
return 0;
}
登录连接数据库的连接字符串很容易写错。上图中我因为在server中少写了【,1433】,就报了[Microsoft][ODBC SQL Server Driver][DBNETLIB]无效的连接的错误。
2、其他(略)