Today’s post is about a project I’ve recently started working on, it’s a C++ application for Linux built with GTK+ and SQL Server vNext for Linux. I’m also using CLion which is my favorite cross-platform IDE when doing plain C++ and Glade as my UI editor.
I chose not to use Qt, because I’d like to demonstrate how to use disparate tools and editors at our disposal to being able to put a solution together. Qt like Visual Studio provides pretty much a comprehensive and complete development environment, and Qt is awesome but it’s very similar to MFC in that aspect, once one starts building a solution with it, it has to be used all along.
I’m using g++ (compiling with –std=c++14, actually) in conjunction with UnixODBC and FreeTDS (information on how to install these two here in this post) to access SQL Server vNext running on another Linux-based PC. I have structured the solution as an MVC solution, besides having a DAL responsible to perform operations in the database.
The way ODBC works is through handles (mostly for environment, connections and statements) that are prepared prior executing any command on the database server. This is where having something similar to using statement in C# comes in handy. As you must be aware, the using statement besides being able to dispose of an object (most of the times, specially when object enclosed in it doesn’t hold any strong or pinned references) provides developers with the opportunity to execute code in an “atomic” fashion, in order to explain this better refer to code snippet below that enables and enforces a transaction when multiple threads are writing to a database, if an error condition is encountered everything is rolled back in the database, but more importantly the resources in use are disposed of, it’s similar to the principle of “unit of work” pattern.
This is one of the cool things about C#, the language takes care of resources once we have finished using them, but lazy developers (and there are quite a lot) can’t be bothered to do it right, so find themselves producing leaky code. Now, back to having something similar to using in C++, refer to SqlDal class below and see a function template called “Using” that takes a lambda as the argument. The lambda contains the code that will make use of the resources allocated and released by function template.
The method that implements “Using” is RetrieveRecords depicted below.
The executing code is also shown in the image below. Please note the information returned from SQL in the form of the Contact model.
And this one depicts SQuirreL querying the demo database via SQL Server’s JDBC driver. I had to use ODBC instead of the JDBC driver, because the latter is Java based (it’s a jar file) which might’ve required me to host the JVM and use JNI and that’s not the scope or purpose of the application. I’ll publish the solution in its entirety once I’ve completed it.