MySQL C++ connector fails without an error message - c++

I'm having trouble with the simple task of creating a connection to a MySQL database in C++. No errors are printed except for the program return value, which is -1.
I'm using Eclipse Oxygen as the IDE, and the OS is Ubuntu 16.04. The MySQL connector version is 1.1.9., and it's the generic Linux version (glibc 2.12).
The connector files reside in my home folder. I've added the directory path of the "include" folder to Properties -> C/C++ Build -> Settings -> GCC C++ Compiler -> Includes. I've also added the "lib" path and "mysqlcppconn" library name to Properties -> C/C++ Build -> Settings -> GCC C++ Linker -> Libraries and Library search path, respectively. Finally, I've added the "lib" path into the LD_LIBRARY_PATH environment variable in Properties -> Run/Debug Settings -> (Launch configuration) -> Environment.
DBManager.cpp:
DBManager::DBManager() {
try {
std::cout << "Getting driver instance" << std:endl;
driver = sql::mysql::get_mysql_driver_instance();
std::cout << "Creating connection" << std::endl;
connection = driver->connect("tcp://127.0.0.1:3306", "username", "password");
std::cout << "Connected!" << std::endl; // NOT REACHING THIS LINE
} catch(const SQLException& ex) {
// these lines are not printed
std::cout << "Exception!" << std::endl;
std::cout << ex.what() << std::endl;
exit(1);
}
}
DBManager::~DBManager() {
std::cout << "Deleting connection" << std::endl;
delete connection;
}
DBManager.h
#ifndef DBMANAGER_H_
#define DBMANAGER_H_
#include <iostream>
#include <mysql_connection.h>
#include <mysql_driver.h>
#include <cppconn/exception.h>
class DBManager {
public:
DBManager();
virtual ~DBManager();
private:
sql::mysql::MySQL_Driver* driver;
sql::Connection* connection;
};
#endif
main.cpp
#include <iostream>
#include "DBManager.h"
int main(int argc, char* argv[]) {
std::cout << "Starting" << std::endl;
DBManager* dbManager = new DBManager();
// ... program logic not reached
delete dbManager; // not reached
return 0;
}

I finally got it to work, I was using the generic Linux binaries first, which did not work. When I switched to using the binaries for Ubuntu, the program started to work.

Related

C++ cpp-net lib not found

Here is a piece of code which is an example from cpp-netlib
#include <boost/network/protocol/http/server.hpp>
#include <string>
#include <iostream>
namespace http = boost::network::http;
struct hello_world;
typedef http::server<hello_world> server;
struct hello_world {
void operator() (server::request const &request,
server::response &response) {
std::string ip = source(request);
response = server::response::stock_reply(
server::response::ok, std::string("Hello, ") + ip + "!");
}
};
int
main(int argc, char * argv[]) {
if (argc != 3) {
std::cerr << "Usage: " << argv[0] << " address port" << std::endl;
return 1;
}
try {
hello_world handler;
server server_(argv[1], argv[2], handler);
server_.run();
}
catch (std::exception &e) {
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
But on compiling that is g++ main.cpp -o socke.exe -lboost_system I get the following errors
main.cpp:1:50: error: boost/network/protocol/http/server.hpp: No such file or directory
main.cpp:5: error: âboostâ has not been declared
I have installed the cpnet-lib libraries and cmake for build them. I cant get to understand why couldnt the compiler find the libraries.
You didn't specify include path where Boost and cpp-netlib headers are located. The first error line tells which header is missing. Assuming your Boost headers are installed under /a/my_boost (i.e. there is a /a/my_boost/boost subdirectory with headers) and cpp-netlib under /a/my_cpp-netlib, you need to add -I command line options for your compiler:
g++ main.cpp -o socke.exe -I/a/my_boost -I/a/my_cpp-netlib -lboost_system
If you're using a graphical IDE or a build system, there should be an option in the project settings to add include directories.

res->getString(1) mysql connector crash debug

I have a problem when i use mysql connector c++ and visual studio on the debug mode. It compiles just fine. My algorithm works on release mode. When i switch to debug mode, he complies but he crash while running.
I believe that he crash each time i use res->getString() .
I m using visual studio 2013, mysql connector.C++ 1.1 . I already added the dependencies
C:\Program Files\MySQL\Connector.C++ 1.1\lib\debug
C:\Program Files\Boost SDK;
C:\Program Files\MySQL\Connector.C++ 1.1\include
mysqlcppconn.lib and mysqlcppconn.dll
CPPCONN_PUBLIC_FUNC= ;HAVE_INT8_T=1 ( on the processor definition)
run time library : /MDd ( it the only think that works )
I copied mysqlcppconn.lib and mysqlcppconn.dll in the debug directory of my project
with this configuration my programm works on release mode ( changing Connector.C++ 1.1\lib\debug to Connector.C++ 1.1\lib\opt ).
In the debug mode, he says Debug Assertion failed :
File: f:\dd\vctools\crt\crtw32\misc\dbgheap.c
Line 1322
Expression : _CrtIsValidHeapPointer( pUserData)
Press Rety to debug the application
then i had to choose one buttom ( Ignore; Restart ; leave ). When i press Ignore he continue to run i have the first results but he crashs again
This is my code section
{
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <memory>
#include <string>
/* MySQL Connector/C++ specific headers */
#include <cppconn/driver.h>
#include <cppconn/connection.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/resultset.h>
#include <cppconn/metadata.h>
#include <cppconn/resultset_metadata.h>
#include <cppconn/exception.h>
#include <cppconn/warning.h>
#include "mysql_connection.h"
using namespace std;
using namespace sql;
int main(int argc, const char **argv)
{
const char* str_DataBaseMarketData_Server = "root";
const char* str_DataBaseMarketData_User = "root";
const char* str_DataBaseMarketData_Password ="root";
const char* str_DataBaseMarketData_Database ="bd test";
cout << "Connector/C++ tutorial framework..." << endl;
cout << endl;
string fld;
try {
sql::Driver* driver = get_driver_instance();
std::auto_ptr<sql::Connection> con(driver->connect(str_DataBaseMarketData_Server, str_DataBaseMarketData_User, str_DataBaseMarketData_Password));
con->setSchema(str_DataBaseMarketData_Database);
std::auto_ptr<sql::Statement> stmt(con->createStatement());
sql::SQLString *data = new SQLString();
std::auto_ptr<sql::ResultSet> res(stmt->executeQuery("SELECT * FROM news "));
//ResultSetMetaData *res_meta = res->getMetaData();
//cout << res_meta->getColumnDisplaySize( 1) << endl << endl;
while (res->next()){
fld = res->getString(2).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)
*/
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
/* Use what() (derived from std::runtime_error) to fetch the error message */
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
return EXIT_FAILURE;
}
cout << "Done." << endl;
return EXIT_SUCCESS;
}
}
This things turns me crazy because when i replace getString() by anything else, it works sweetly.Could you help me please ?
I m running under a 32 bit.

mkdir() returns -1 when launched through Finder

I have a simple program that makes a directory when it is executed:
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(){
if(int a = mkdir("abc",0700)){
std::cout << "Failed to create: " << a << std::endl;
}
else{
std::cout << "Created." << std::endl;
}
}
It behaves differently for two different use cases:
Running the compiled binary through Terminal
Output: Created.
Launching this program via Finder with double click.
Output: Failed to create: -1
How do I make this so that launching this program via Finder creates the folder abc without using Cocoa framework (compiles with g++ only)?
Thanks to Wooble for pointing it out in the comment section that the problem is due to the working directory. When I launched it through Finder, the current working directory was my home directory.
Below is how I address the problem:
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <libproc.h>
int main(int argc, char** argv){
// Gets and prints out the current directory
char cwd[1024];
getcwd(cwd, sizeof(cwd));
std::cout << "Current Working Directory: " << cwd << std::endl;
// Above is not necessary
// Changes working directory to directory that contains executable
char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
if(proc_pidpath (getpid(), pathbuf, sizeof(pathbuf)) > 0){ // Gets the executable path
std::string s(pathbuf);
s = s.substr(0,s.find_last_of('/')); // Removes executable name from path
std::cout << "Executable Path: " << s << std::endl;
chdir(s.c_str()); // Changes working directory
}
if(int a = mkdir("abc",0700)){
std::cout << "Failed to create: " << a << std::endl;
}
else{
std::cout << "Created." << std::endl;
}
}

Connection attempt failed MySQL poco

Another question on a Mysql connection failing:
I'm using the Poco library (1.5.2) and I would like to know why, when I try to open a MySQL connection, I got this message:
Connection attempt failed
Whereas, when I try a connection via console (mysql -u root -p ...), it works.
Maybe I forget an important step in the MySQL configuration ?
Here is my code :
#include <iostream>
#include <string>
#include <Poco/Data/MySQL/MySQLException.h>
#include <Poco/Data/MySQL/Connector.h>
#include <Poco/Data/SessionFactory.h>
using namespace std;
int main()
{
Poco::Data::MySQL::Connector::registerConnector();
try
{
string str = "host=localhost;user=root;password=mypassword;compress=true;auto-reconnect=true";
Poco::Data::Session test(Poco::Data::SessionFactory::instance().create(Poco::Data::MySQL::Connector::KEY, str ));
}
catch (Poco::Data::MySQL::ConnectionException& e)
{
cout << e.what() << endl;
return -1;
}
catch(Poco::Data::MySQL::StatementException& e)
{
cout << e.what() << endl;
return -1;
}
return 0;
}
Thank you !!
ok the problem was the "localhost" value for "host" doesn't work on my linux (I don't know why). For fixing the bug, I had to change my string to:
string str = "host=127.0.0.1;user=root;password=mypassword;compress=true;auto-reconnect=true";

log4cpp gives `unresolved external` errors

I'm trying to make work the library and run the tests provided with the latest version of log4cpp on Borland Codegear 2007, in which it's included a bpr project for Borland C++ Builder 5, which is meant to be able to build and run the different tests. The problem is that I'm trying to open this project with the 2007 version, which has to carry out a project conversion. I was getting weird 'unresolved external' errors. Then I've tried to build the project myself without converting anything, but got stuck in the same point.
I'm trying to run the following test :
#include <stdio.h>
#include "log4cpp/Portability.hh"
#ifdef LOG4CPP_HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <iostream>
#include "log4cpp/Category.hh"
#include "log4cpp/Appender.hh"
#include "log4cpp/FileAppender.hh"
#include "log4cpp/OstreamAppender.hh"
#ifdef LOG4CPP_HAVE_SYSLOG
#include "log4cpp/SyslogAppender.hh"
#endif
#include "log4cpp/Layout.hh"
#include "log4cpp/BasicLayout.hh"
#include "log4cpp/Priority.hh"
#include "log4cpp/NDC.hh"
int main(int argc, char** argv) {
log4cpp::Appender* appender;
#ifdef LOG4CPP_HAVE_SYSLOG
log4cpp::SyslogAppender* syslogAppender;
syslogAppender = new log4cpp::SyslogAppender("syslog", "log4cpp");
#else
log4cpp::Appender* syslogAppender;
syslogAppender = new log4cpp::OstreamAppender("syslogdummy", &std::cout);
#endif
if (argc < 2) {
appender = new log4cpp::OstreamAppender("default", &std::cout);
} else {
appender = new log4cpp::FileAppender("default", argv[1]);
}
syslogAppender->setLayout(new log4cpp::BasicLayout());
appender->setLayout(new log4cpp::BasicLayout());
log4cpp::Category& root = log4cpp::Category::getRoot();
root.addAppender(syslogAppender);
root.setPriority(log4cpp::Priority::ERROR);
log4cpp::Category& sub1 = log4cpp::Category::getInstance(std::string("sub1"));
sub1.addAppender(appender);
log4cpp::Category& sub2 = log4cpp::Category::getInstance(std::string("sub1.sub2"));
log4cpp::NDC::push(std::string("ndc1"));
std::cout << " root prio = " << root.getPriority() << std::endl;
std::cout << " sub1 prio = " << sub1.getPriority() << std::endl;
std::cout << " sub2 prio = " << sub2.getPriority() << std::endl;
root.error("root error");
root.warn("root warn");
sub1.error("sub1 error");
sub1.warn("sub1 warn");
sub2.error("sub2 error");
sub2.warn("sub2 warn");
sub1.setPriority(log4cpp::Priority::INFO);
std::cout << " root prio = " << root.getPriority() << std::endl;
std::cout << " sub1 prio = " << sub1.getPriority() << std::endl;
std::cout << " sub2 prio = " << sub2.getPriority() << std::endl;
std::cout << "priority info" << std::endl;
root.error("root error");
root.warn("root warn");
sub1.error("sub1 error");
sub1.warn("sub1 warn");
sub2.error("sub2 error");
sub2.warn("sub2 warn");
sub2.warnStream() << "streamed warn";
sub2 << log4cpp::Priority::WARN << "warn2" << " warn3"
<< log4cpp::eol << " warn4";
{
for(int i = 0; i < 10000; i++) {
char ndc2[20];
sprintf(ndc2, "i=%d", i);
log4cpp::NDC::push(ndc2);
sub1.info("%s%d", "i = ", i);
if ((i % 10) == 0) {
sub1.log(log4cpp::Priority::NOTICE, "reopen log");
if (log4cpp::Appender::reopenAll()) {
sub1.info("log reopened");
} else {
sub1.warn("could not reopen log");
}
}
#ifndef WIN32
sleep(1);
#endif
log4cpp::NDC::pop();
}
}
return 0;
}
The errors are all about 'unresolved external', such as:
[ILINK32 Error] Error: Unresolved external 'log4cpp::Category::warn(const char *, ...)' referenced from C:\DOCUMENTS AND SETTINGS\MLERMA\MIS DOCUMENTOS\RAD STUDIO\PROJECTS\DEBUG\TESTMAIN.OBJ
I'm getting this kind of error for every single call to a log4cpp function, all referring to TESTMAIN.OBJ .
Any ideas on this? is there anyone out there who has worked with log4cpp on Borland ?
Are you linking in the log4cpp library (.LIB)? I'm not familiar with BCB5 or Codegear but check your link libraries in your project settings and make sure the log4cpp library is included.
If it is, then you might have a problem with where the compiler is looking for libraries. Usually an IDE will have a project level or global setting that says where there compiler will look for .lib files. Check that setting and make sure one of those directories includes your log4cpp .lib file.
Mike
Try adding #pragma comment(lib,"ws2_32.lib") do your header file.