Search code examples
sqlcommand-line-interfacec++-cli

C++/CLI SQL use ConnectionString with parameters as string


Trying to connect to SQL Server in VS2019 C++/CLI app. This code works for me:

#include "pch.h"
#include <iostream>

#using < System.dll>
#using < System.Data.dll>

using namespace std;
using namespace System;
using namespace System::Data;
using namespace System::Data::SqlClient;

bool ConnectToSQLServer(string server)
{
    SqlConnection cnn;
    cnn.ConnectionString = "Server=.\\SQLExpress;Integrated Security=SSPI;database=master";
    try
    {
        cnn.Open();
        cnn.Close();
        return true;
    }
    catch (SqlException ^ex)
    {
        return false;
    }

}

int main()
{
    if (ConnectToSQLServer(".\\SQLExpress"))
        printf("Connected!");
    else
        printf("Can not connect to SQL server!");

    return 0;
}

but when I change ConnectionString to this:

cnn.ConnectionString = "Server="+ server +";Integrated Security=SSPI;database=master";

I get compiler error:

Error (active) E1767 function "System::Data::SqlClient::SqlConnection::ConnectionString::set" cannot be called with the given argument list

The same error when I'm trying to use SqlConnectionStringBuilder:

SqlConnectionStringBuilder sqlBuilder;

sqlBuilder.DataSource = server;

So how to use string type parameters in ConnectionString?


Solution

  • In CLR/CLI c++ you should not use string which is ambiguous. it may be std::string which is a different type from .NET's string. in particular it hard to tell when you use: using namespace std;.

    What you should do is to use String^ which is a reference to a .NET class.

    so your code should be something like:

    bool ConnectToSQLServer(String^ server)
    {
        SqlConnection cnn;
        cnn.ConnectionString =  String::Format("Server={0};Integrated Security=SSPI;database=master", server);
        try
        {
            cnn.Open();
            cnn.Close();
            return true;
        }
        catch (SqlException ^ex)
        {
            return false;
        }
    }
    

    And you can call it like this:

    ConnectToSQLServer(gcnew String(".\\SQLExpress"));