I've been trying to use the mysql++ library in my application (windows x64 based) but I can't seem to connect to my sql server.
Some information:
I used this code to connect to the server:
mysqlpp::Connection conn(db, 0, user, pass, 3306);
this definitely has the right data in it.
and then, my sql server is the standard service from the MySQL install. And I'm pretty sure I used the standard settings. I can connect to it using the MySql Workbench and I edited some new tables and such but my own program doesn't seem to connect.
I read the documentation and I can't find anything specific that might suggest something why I can't connect.
Oh, so many issues, so little time...
Have you checked that your program has permissions to access the database?
Does your program have the correct privileges?
Is your host name correct?
What errors are you getting?
What exception is thrown?
When you use the debugger, what line is the error on?
Here's my method:
sql::Connection * const
Manager ::
get_db_connection(void) const
{
//-------------------------------------------------------------------------
// Use only one connection until proven that more connections will make
// the program more efficient or have a beneficial impact on the user.
// Thus the change in returning sql::Connection * rather than a smart pointer.
// A smart pointer will delete its contents.
//-------------------------------------------------------------------------
static const char host_text[] = "tcp://127.0.0.1:3306/";
static std::string host_name;
if (!m_connection_initialized)
{
host_name = host_text;
initialize_db_driver();
host_name += m_dataset_info.m_dsn_name;
try
{
m_p_connection = m_p_sql_driver->connect(host_name.c_str(),
m_dataset_info.m_user_name.c_str(),
m_dataset_info.m_password.c_str());
}
catch (sql::SQLException &e)
{
/*
The MySQL Connector/C++ throws three different exceptions:
- sql::MethodNotImplementedException (derived from sql::SQLException)
- sql::InvalidArgumentException (derived from sql::SQLException)
- sql::SQLException (derived from std::runtime_error)
*/
wxString wx_text = wxT("# ERR: SQLException in ");
wx_text += wxT(__FILE__);
wxLogDebug(wx_text);
wx_text.Printf(wxT("# ERR: (%s) on line %d"),
__FUNCTION__,
__LINE__);
wxLogDebug(wx_text);
wx_text.Printf(wxT("# ERR: %s (MySQL error code: %d, SQLState: %s)"),
e.what(),
e.getErrorCode(),
e.getSQLState());
wxLogDebug(wx_text);
wxLogDebug(wxT("Verify that mysqlcppconn.dll is in the PATH or in the working directory."));
// throw Manager_Connection_Not_Initialized();
m_connection_initialized = false;
}
catch (...)
{
std::cout << "Unhandled database SQL exception\n" << flush;
m_connection_initialized = false;
}
m_connection_initialized = true;
}
return m_p_connection;
}
Related
I have a Zaber linear stage for which I'm developing a C++ backend, to integrate it in my framework.
I have installed the Zaber API by following the instructions from the Zaber webpage. The installer actually generates the dll, lib, and headers necessary for my backend, and I'm confident that my CMake configuration is correct, because I can instantiate objects from the Zaber API.
So now, I am trying in my framework to go through their first code example:
// I commented out the following block:
// - enableDeviceDbStore() is supposed to allow the library to cache
// information from the online database
// - I don't need the online db
// - when I call it, it throws a "string too long" exception.
// try
// {
// zaber::motion::Library::enableDeviceDbStore(".");
// }
// catch (std::exception& e)
// {
// LogError << e.what();
// }
try
{
_connection = zaber::motion::ascii::Connection::openSerialPort("COM6");
// this also throws a "string too long" exception
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
std::vector<zaber::motion::ascii::Device> deviceList;
try
{
deviceList = _connection.detectDevices(false);
// this throws a "Connection has been closed" exception
}
catch (std::exception& e)
{
std::count << e.what() << std::endl;
}
std::count << "Found " << deviceList.size() << " devices." << std::endl;
The problem is, when I use the Zaber Launcher (their UI that allows to control a connected stage), the port is "COM6", and I have made sure to close the connection on the Zaber Launcher before trying to connect with my framework.
I have also tried to launch their pre-configured C++ code example (VS17 solution), with the same problems arising (except their example doesn't catch exceptions, so it just crashes).
None of my exception matches their troubleshooting section.
I don't know how to proceed from here, or how to interpret the "string too long" error message, considering that I'm sure of my connection port.
My environment is: Windows 10 , Microsoft SQL Server 2017 Developer Edition.
I'm using c++ ADO to connect to sql server, but when it is connecting to the server, it throw an error, but return null error information.
Below is my codes,
// ms_connection.h
#import "C:\Program Files (x86)\Common Files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF")rename("BOF","adoBOF")
class MSConnection
{
public:
virtual void init();
virtual void connect();
private:
_ConnectionPtr m_connection;
};
// ms_connection.cpp
#include "ms_connection.h"
void MSConnection::init()
{
try
{
m_connection.CreateInstance("ADODB.Connection");
}
catch (_com_error e)
{
LOG_ERROR << "MSConnection failed when try to init the object, " << (const char*)e.Description();
throw (const char*)e.Description();
}
}
void MSConnection::connect()
{
try
{
m_connection->Open(L"Provider=SQLOLEDB;Data Source=127.0.0.1, 1443;", L"root", L"haiwell", adModeUnknown);
}
catch (_com_error e)
{
LOG_ERROR << "MSConnection failed when try to connect to the server, " << (const char*)e.Description();
throw (const char*)e.Description();
}
}
When execute the init() and connect(), I found an error in log,
2019-05-15 11:00:18.343 ERROR [14408] [MSConnection::connect#36] MSConnection failed when try to connect to the server, (null)
I have restarted my computer and sql server, but the problem is still existed.
Could someone give me any advice? Why is it so strange?
Thanks a lot in advance.
Just add ::CoInitialize(NULL); in the same function of Open, will be ok.
PROBLEM: What's the cause of the memory leaks?
SITUATION:
I've build a simple command line program using C++ together with MySQL using the MySQL C API
The problem is, the program has many "minor" memory leaks from the object malloc xx bytes" with xx ranging from a few bytes to 8 kb. All of the leaks links to the library libmysqlclient.18.dylib.
I've already removed all the mysql_free_result() from the code to see if that was the problem, but its still the same.
My MySQL code mainly consists of simple code like:
to connect:
MYSQL *databaseConnection()
{
// declarations
MYSQL *connection = mysql_init(NULL);
// connecting to database
if(!mysql_real_connect(connection,SERVER,USER,PASSWORD,DATABASE,0,NULL,0))
{
std::cout << "Connection error: " << mysql_error(connection) << std::endl;
}
return connection;
}
executing a query:
MYSQL_RES *getQuery(MYSQL *connection, std::string query)
{
// send the query to the database
if (mysql_query(connection, query.c_str()))
{
std::cout << "MySQL query error: " << mysql_error(connection);
exit(1);
}
return mysql_store_result(connection);
}
example of a query:
void resetTable(std::string table)
{
MYSQL *connection = databaseConnection();
MYSQL_RES *result;
std::string query = "truncate table " + table;
result = getQuery(connection, query);
mysql_close(connection);
}
First of all: Opening a new connection for every query (like you're doing in resetTable()) is incredibly wasteful. What you really want to do is open a single connection when the application starts, use that for everything (possibly by storing the connection in a global), and close it when you're done.
To answer your question, though: You need to call mysql_free_result() on result sets once you're done with them.
I am writing a multi-threaded application in C++ using Boost threads (pthread). The application spawns 100 threads and each thread does the following task (I am writing a code snippet that will be running in each thread):
try {
driver = get_driver_instance();
con = driver->connect(SettingsClass.HostName, \
SettingsClass.UserName,SettingsClass.Password);
// SettingsClass is a global static class whose members
// (HostName, UserName, Password, etc) are initialized once
// before *any* thread is created.
con->setSchema("MyDatabase");
driver->threadInit();
string dbQuery = "select A, B, C from XYZTable where D=?";
prepStmt = con->prepareStatement(dbQuery);
prepStmt->setInt(1, 1);
rSet = prepStmt->executeQuery();
/* Do Something With rSet, the result set */
delete rSet;
delete prepStmt;
if (con != NULL && !con->isClosed()) {
con -> close();
driver->threadEnd();
delete con;
}
catch (SQLException &e)
{
/* Log Exception */
}
On running the process (the app, as earlier mentioned, i.e. with 100 such threads), I attach gdb midway and observe that more than 40% of the threads have hanged in the read() call. All the backtraces have mysql library functions (vio_read(), etc) and none are from my code as my code does not perform any I/O.
Could anyone point out why is this issue arising. Should I check my code / network or MySQL server configuration? Have I used the C++ connector library properly?
I have an java app for blackberry, created with Java Plug-in for Eclipse. I want to invoke a webservice on a webserver through Blackberry mds. The code I am using works, but is not stabile. Meaning that I get successfully get in contact with web server 100 times in a row, but after a while, the connection is broken. The log files from Blackberry are many and not easy to read, but at least I a feel that the phrase "Invalid socket" is not good for me.
I am using StreamConnection class in my code, but I see from some sample code that httpConnection is used instead. Anyone know when to use HttpConnection instead of StreamConnection?
I paste my code here. Perhaps some of you see anything I should have done different:
private boolean sendStatusMessage(String phoneNumber, String status) {
StreamConnection conn = null;
OutputStream output = null; //mari added
try {
String body = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:i3w=\"http://I3WebAction\">"
+ "<soapenv:Header/>"
+ "<soapenv:Body>"
+ "<i3w:I3SetMobileStatus><i3w:p_Status>"
+ status
+ "</i3w:p_Status><i3w:p_PhoneNumber>"
+ phoneNumber
+ "</i3w:p_PhoneNumber>"
+ "</i3w:I3SetMobileStatus></soapenv:Body></soapenv:Envelope>";
String URL = "socket://" + soapServer + ":" + port
+ ";deviceside=false";
conn = (StreamConnection) Connector.open(URL);
//OutputStream output = conn.openOutputStream();
output = conn.openOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(output);
writer.write("POST /SOAPListener/I3SOAPISAPIU.dll HTTP/1.1\r\n");
writer.write("Accept-Encoding: gzip,deflate\r\n");
writer.write("Content-Type: text/xml;charset=UTF-8\r\n");
writer.write("SOAPAction: \"http://I3WebAction/I3SetMobileStatus\"\r\n");
writer.write("User-Agent: Jakarta Commons-HttpClient/3.1\r\n");
writer.write("Host: lvkdb01\r\n");
writer.write("Content-Length: " + body.length() + "\r\n");
writer.write("\r\n");
writer.write(body);
writer.flush();
writer.close(); //mari added
} catch (Exception e) {
Dialog.alert(e.getMessage());
return false;
} finally {
try {
// Close stream regardless of exceptions and return-points
output.close();
} catch (IOException e) {
// If closing the stream causes exception, the stream is most
// likely not open or available. We display an error message,
// and continues the program.
Dialog.alert(e.getMessage());
return false;
}
try {
// Close stream regardless of exceptions and return-points
conn.close();
} catch (IOException e) {
// If closing the stream causes exception, the stream is most
// likely not open or available. We display an error message,
// and continues the program.
Dialog.alert(e.getMessage());
return false;
}
}
return true;
}
I appreciate any comments or ideas on why this code is not running stabile.
By default all requests through BES are transcoded. Try to turn off transcoding and see if that resolves your issue. To turn off transcoding you would need to pass the below header.
Turn off MD transcoding: ("x-rim-transcode-content", "none) as a header
MDS logs would be useful(default location c:\Program Files\Research In Motion\BlackBerryEnterprise Server\Logs)/
They end with “MDAT”. The logging level can be changed by following these instructions.
http://docs.blackberry.com/en/admin/deliverables/14334/Change_logging_level_for_MDSCS_552126_11.jsp
You may also way to enable Verbose HTTP logging for testing, found here, which can help trace through the http messages.
http://docs.blackberry.com/en/admin/deliverables/14334/Change_activities_MDSCS_writes_to_log_827932_11.jsp