c++ - sql连接?

标签 c++ sql-server sqlapi++

我使用 SQLAPI++ 将我的程序连接到数据库。

下面的代码编译没有错误。但是它不连接到数据库。我收到一条错误消息:

A network-related or instance-specific error occurred while establishing a connection
to
SQL Server.
The server was not found or was not accessible. 
Verify that the instance name is correct and that SQL Server is configured to allow 
remote connections. 
(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
ExecuteNonQuery requires an open and available Connection. 
The connection's current state is closed.

我已经检查过我的服务器上启用了远程连接并且启用了 TCI/IP。我还尝试过向防火墙添加端口异常(exception),但失败了,我什至尝试关闭防火墙。 -还有我的杀毒软件。

所以我相信这与我的代码有关。任何人都可以找到任何错误吗?

#include <iostream>
#include "SQLAPI\include\SQLAPI.h"
#include <string>
#include <Windows.h>


using namespace std;

int main(int argc, char* argv[])
{

SAConnection con; 

try
{ 
    con.Connect(

    "BLAKE\\SQLEXPRESS@ERP",     // db *& server?!*
        "sa",   // user
        "blake",   // password
    SA_SQLServer_Client);



}
catch (SAException &x)
{
    // SAConnection::Rollback()

    try
    {
        // on error rollback changes
        con.Rollback();
    }
    catch (SAException &)
    {
    }

    cerr << (const char*)(x.ErrText()) << endl;

}



return 0;
}

最佳答案

首先,您可能希望禁用命名管道协议(protocol),并强制仅通过 TCP/IP 进行连接。

之后,由于您指定了实例名称,因此您需要打开两个防火墙端口。一个用于 SQL 浏览器服务,它告诉 SQL 客户端运行 SQL 的端口实例,另一个用于 SQL Server 本身。默认情况下,命名实例运行的端口是随机的(因此需要浏览器服务监听固定端口),但您可以将其更改为固定端口。

您还需要首先确保 SQL 浏览器服务正在运行。

您还可以将 SQL 正在监听的端口粘贴到服务器规范的连接字符串中,例如服务器\实例,端口。这意味着您不需要直接连接到浏览器服务。

关于c++ - sql连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23168661/

相关文章:

c++ - Armadillo 不执行交换优化

C++ 类和嵌套成员

c++ - 如何在类构造函数中初始化 ifstream 对象?

c++ - 为什么 "error: invalid application of ' sizeof' 为使用 unique_ptr 的不完整类型”通过添加空析构函数来修复?

sql - 根据两对组合的权重找到最接近的数字

c++ - 无法通过 SQLApi++ 连接到 MemSQL

sql-server - NVARCHAR(MAX) - 作为 SQL 存储过程输出参数

sql-server - 计算每月的小时数

java - 使用 MSSQL 的 Hibernate joined-subclass 死锁