C++语言Sql Server链接不上问题思路补充,给你一个新的参考

本文详细介绍了使用C++和otl第三方库连接SqlServer数据库的过程,包括前期准备、测试用例编写,以及解决连接字符串配置错误的常见问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

因为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、其他(略)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值