Connecting to a local database using mysql-cpp-connector - c++

Introduction
I am new to using mysql in c++ and have been trying to use mysqlcppconnector for connecting to my local database. I have successfully linked the libraries after a lot of effort. (It wasn't straightforward for me)
Preparation
I am using the following code to connect with a database running on my local.
#include <mysqlx/xdevapi.h>
void make_db_connection() {
mysqlx::Session sess("localhost", 33060, "mudrex", "mudrex");
mysqlx::Schema db= sess.getSchema("mudrex");
// or Schema db(sess, "test");
mysqlx::Collection myColl = db.getCollection("user_api_key_map");
// or Collection myColl(db, "my_collection");
mysqlx::DocResult myDocs = myColl.find("user_id")
.limit(1)
.bind("user_id","L%").execute();
cout << myDocs.fetchOne()<<endl;
}
Errors
When I call the above function, I get the following error :
libc++abi.dylib: terminating with uncaught exception of type mysqlx::abi2::r0::Error: CDK Error: Connection refused (generic:61)
Abort trap: 6
Any help would be really appreciated. Thank you for your time.

mysqlx::Session is for connection to the MySQL X protocol. The Error: Connection refused is the very first hint of missing listeners of the port 33060. You need to install and enable the MySQL Shell that supports X Protocol and enables you to use X DevAPI. See https://dev.mysql.com/doc/mysql-shell/en/mysql-shell-install.html for instructions.

Related

Proper error handling for OCCI C++ library

I want to understand how should I correctly handle exceptions in OCCI C++ library (https://docs.oracle.com/database/121/LNCPP/relational.htm#LNCPP003).
Below is simple example of creating connection, statement and executing statement.
Environment *env = Environment::createEnvironment();
Connection *conn = env->createConnection(
userName, password, connectString);
Statement *stmt = conn->createStatement(
"SELECT blobcol FROM mytable");
try {
stmt->execute();
} catch (oracle::occi::SQLException &ex) {
// what to do here?
}
My questions are:
Is there a standardized way to handle occi::SQLException? In perfect world I want to know on which exceptions I can safely just retry my stmt->execute and have a possibility to get successful result. I figured out that occi::SQLException has a member is SQLException::isRecoverable(), does it mean I can just retry on all these recoverables errors without reconnect etc.? Is there a documented list of this recoverable errors?
How to know if connection lost? Is there a known list of sql codes for lost connection case?
If connection lost what is the correct way to recover? Should I get rid of old Connection object and create new connection with env->createConnection and hence I have to recreate all statements using new connection? Or maybe I should just retry executing my statements and connection with automatically recover inside OCCI driver library?

Kafka alPakka throwing compile issues when using restart source

Trying to use restart with source in case of Kafka rebalance , however below code is throwing error when using Alpakka Kafka library
Throwing complies error while using below code
Caused by: java.lang.ClassCastException: akka.NotUsed$ cannot be cast to java.util.concurrent.CompletionStage
CompletionStage<Done> streamCompletion =
RestartSource.onFailuresWithBackoff(
restartSettings,
() ->
Consumer.plainSource(consumerSettings, Subscriptions.topics(topic))
.mapMaterializedValue(
c -> {
// this is a hack to get access to the Consumer.Control
// instances of the latest Kafka Consumer source
control.set(c);
return c;
})
.via(business()))
.runWith(Sink.ignore(), system);

SignalR-Client-Cpp on Petalinux Throwing "Error in SSL handshake" Exception

I have a Xilinx ZCU106 with a Petalinux build I created that includes an application using SignalR-Client-Cpp. Despite trying a number of things, I'm continually getting an "Error in SSL handshake" exception after calling start() on my signalr::hub_connection.
This application runs fine on other Linux systems like Ubuntu. I think the problem is it's having trouble finding the ca-certificates.crt file which is usually in /usr/local/ssl on more normal Linux distro's like Ubuntu. In the Petalinux build it's located here: /etc/ssl/certs/ca-certificates.crt.
The best I can tell, I need to do something like this to configure the signalr::hub_connection to use the certificate file:
web::http::client::http_client_config httpConfig;
httpConfig.set_ssl_context_callback([](boost::asio::ssl::context& ctx) {
ctx.load_verify_file("/etc/ssl/certs/ca-certificates.crt"); });
web::websockets::client::websocket_client_config wsConfig;
wsConfig.set_ssl_context_callback([](boost::asio::ssl::context& ctx) {
ctx.load_verify_file("/etc/ssl/certs/ca-certificates.crt"); });
signalr::signalr_client_config signalrConfig;
signalrConfig.set_http_client_config(httpConfig);
signalrConfig.set_websocket_client_config(wsConfig);
auto hubConn = signalr::hub_connection_builder::create(signalrURI).build();
hubConn.set_client_config(signalrConfig);
std::promise<void> task;
hubConn.start([&task](std::exception_ptr exception) {
// Code that checks the exception, etc
Yet, even when doing this, the exception that is passed into start() is populated, stating "Error in SSL handshake".
I've tried some other things like using web::credentials and setting those on the signalr_client_config before giving it to the hub_connection but I get the same results.
I'm out of ideas as to how to get this to work and I'm hoping someone else might have some ideas?

Using libhttpserver to build https server

I am trying to compile the below piece of code to run a basic https server and i am encountering an error which i am not able to resolve. The class hello_world_resource is responsible for the server startup and the return statement gives the response that the server should give when it is accessed.
the url for the server is defined by function 'register_resource'
the url for the github documentation of the library - https://github.com/etr/libhttpserver
I've tried downloading ssl and curl multiple times and searched the google too but i am still not able to find the cause for this problem.
abcd.key and xyz.crt are the self-signed certificates that i generated following this procedure online -
https://www.digitalocean.com/community/tutorials/how-to-create-a-self-signed-ssl-certificate-for-apache-in-ubuntu-16-04
#include <httpserver.hpp>
using namespace httpserver;
class hello_world_resource : public http_resource
{
public:
const std::shared_ptr<http_response> render(const http_request&)
{
return std::shared_ptr<http_response>(new
string_response("Hello, World!"));
}
};
int main()
{
webserver ws = create_webserver(8080)
.use_ssl()
.https_mem_key("/path/to/abcd.key")
.https_mem_cert("/path/to/xyz.crt");
hello_world_resource hwr;
ws.register_resource("/hello", &hwr);
ws.start(true);
return 0;
}
The error being thrown is :
terminate called after throwing an instance of 'std::invalid_argument'
what(): BD
A
(G BBJ
Aborted
the code should run and a server should be available at - https://localhost:8080/hello

Mysql Connector connect() issues

I have a small C++ project and need to access a mySQL DB from it, so i have setup mySQL Connector for C++.
This is done on OS X 10.10, and i got no problems with the compilation/linking.
I have written a class for all the mysql stuff, and in the constructor i want to setup the connection to the db. However, this seems to be kinda hard.
Here is the relevant part from the class:
class mysql{
public:
mysql(std::string server, std::string user, std::string password);
private:
sql::mysql::MySQL_Driver *driver;
sql::Connection *con;
std::string last_error = "";
};
And here the implementation:
mysql::mysql(std::string server, std::string user, std::string password){
driver = sql::mysql::get_mysql_driver_instance();
try{
con = driver->connect(server, user, password);
last_error = "";
}
catch(sql::SQLException &e){
last_error = e.what();
}
}
However, when i create an object of that class like this:
mysql db("tcp://127.0.0.1:3306", "root", "secretsecret");
I then have this in my last_error string:
Unknown MySQL server host '???' (0)
The "host" sometimes differs even tho i dont change it in code. This seems like internally a different memory location is read out as it should be.
But even if i pass the connect() variables directly when i call it, i get this error. Same when saving those three variables internally in the mysql class and use those to call connect().
Anyone has an idea what could cause this? I have a similar implementation in a different project where this does work fine so im kinda confused :/
Here is a post that matches to your circumstances (The C++ connector works on linux and fails on OSX).
With using mysql logging/tracing or running it in debugger, you may be able to gather more information to report to mysql developers. You may have better luck.
After a long time of googeling i found this the most useful link: https://apple.stackexchange.com/questions/251290/weird-behaviour-of-mysql-connector-c-in-osx
Following the hints there, i recompiled the myscl c connector and then the mysql c++ connector (version 1.1.6 cause 1.1.7 caused a json error while compiling).
I also saw in the cmake logs of the c++ connector that Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ was used to compile the library.
So i used that one too for my compilation. It could be that this would work, tho im also including wxwisgeds in my project resulting in this error:
/usr/local/include/wx-3.0/wx/strvararg.h:30:18: fatal error: 'tr1/type_traits' file not found
#include <tr1/type_traits>
I found some hints for that one but they all just produced a massiv amount of new errors, so i stopped digging deeper here.
My best options would be to create two seperate programs, on to communicate with mysql and one to provide the gui and let them both communicate with each other either via sockets or files providing a very inefficient access to a mysql db.
Good luck to anyone who runs into the same thing..