Reputation: 29
I have _bstr_t
string and I have wchar_t
and one unsigned int
variables which I want to put to the string...
_bstr_t strCnn("Driver={SQL Server};Server=some_host,some_port;Database=some_db;User ID=some_user;Password=some_psw;");
wchar_t *host,
unsigned int port,
wchar_t *db_name,
wchar_t *user,
wchar_t *password,
These 5 variables I pass to the function which does connection. Can you please guide me how to insert them to connection string.
I tried this way:
wstring ws(host);
string host_str(ws.begin(), ws.end());
wstring ws_db(db_name);
string db_str(ws_db.begin(), ws_db.end());
wstring ws_user(user);
string user_str(ws_user.begin(), ws_user.end());
wstring ws_psw(password);
string psw_str(ws_psw.begin(), ws_psw.end());
std::string port_str = std::to_string(port);
_bstr_t strCnn("Driver={SQL Server};Server="+host_str+","+port_str+";Database="+db_str+";User ID="+user_str+";Password="+psw_str+";");
But it says:
Error E0289 no instance of constructor "_bstr_t::_bstr_t" matches the argument list
Error C2664 '_bstr_t::_bstr_t(const _bstr_t &) throw()': cannot convert argument 1 from 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' to 'const char *'
Upvotes: 1
Views: 345
Reputation: 32742
When you construct the string to pass to strCnn
, it is a std::string
object. _bstr_t
does not have a constructor that takes a string
, but does have one that takes const char *
(which is what the error message is telling you.
The simple fix is to construct your string and save that in a local variable, then pass that string (converted to a const char *
) to the _bstr_t
constructor.
std::string port_str = std::to_string(port);
std::string connection = "Driver={SQL Server};Server="+host_str+","+port_str+";Database="+db_str+";User ID="+user_str+";Password="+psw_str+";";
_bstr_t strCnn(connection.c_str());
This may not be the optimal way to construct a string (std::stringstream
may be better).
Since your original parameter strings are wide characters, you can construct the connection string with wide characters (and std::wstring
).
Upvotes: 1
Reputation: 2516
Perhaps the easiest way would be to use std::wstringstream
.
Your code could then look something like:
std::wstringstream ws;
ws << "Driver={SQL Server};Server=" << host << "," << port << ";Database=" << db << ";User ID=" << user << ";Password=" << pswr <<";";
_bstr_t strCnn(ws.str().c_str());
The constructor of _bstr_t
takes a const wchar_t*
so no need to do any intermediary conversions.
Upvotes: 1