How to install MySQL Connector/C++ on Raspberry Pi With Cmake

C++ on Raspberry Pi with Cmake.md

How to install My SQL Connector/C++ on Raspberry Pi With Cmake

1. Install MySQL server

We will first install the MySQL server on Raspberry Pi.

$ sudo apt-get install mysql-server php5-mysql

Note: When you are installing MySQL, you will be asked for a root password. You’ll need to remember the password. We will need it later.

2. Install MySQL Connector for C++

We will need to install this in order to insert/retrive data to/from a MySQL server with C++ language.

$ sudo apt-get install libmysqlclient-dev libmysqlcppconn-dev 

3. Write simple C++ program

First, create main.cpp program, copy the C++ program and save it.

Note: REMEMBER to change the ‘password’ to the root password of MySQL in the program.

Note: The default username is root

$ mkdir MySQLTest
$ gedit main.cpp
/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>

/*
  Include directly the different
  headers from cppconn/ and mysql_driver.h + mysql_util.h
  (and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>

using namespace std;

int main(void) {

    cout << "Started" << endl;

    try {
        sql::Driver *driver;
        sql::Connection *con;
        sql::Statement *stmt;

        /* Create a connection */
        driver = get_driver_instance();
        con = driver->connect("tcp://127.0.0.1:3306", "root", "root"); //IP Address, user name, password

        stmt = con->createStatement();
        stmt->execute("DROP DATABASE IF EXISTS  test_db"); //drop if 'test_db' exists
        stmt->execute("CREATE DATABASE test_db");// create 'test_db' database

        stmt->execute("USE test_db"); //set current database as test_db
        stmt->execute("DROP TABLE IF EXISTS test"); //drop if 'test' table exists
        stmt->execute(
                "CREATE TABLE test(id INT, label CHAR(1))"); //create table with (column name as id accepting INT) and (column name as label accepting CHAR(1))
        stmt->execute("INSERT INTO test(id, label) VALUES (1, 'a')"); //insert into 'test' table with (1 and 'a')

        delete stmt;
        delete con;
        /*According to documentation,
        You must free the sql::Statement and sql::Connection objects explicitly using delete
        But do not explicitly free driver, the connector object. Connector/C++ takes care of freeing that. */

    } catch (sql::SQLException &e) {
        cout << "# ERR: " << e.what();
        cout << " (MySQL error code: " << e.getErrorCode();
        cout << ", SQLState: " << e.getSQLState() << " )" << endl;
    }

    cout << "Successfully ended" << endl;
    return EXIT_SUCCESS;
}

4. Write CMake text file

Create a CMake file and save it.

$ gedit CMakeLists.txt
cmake_minimum_required(VERSION 3.3)
project(MySQLTEST)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

#Ref from https://cmake.org/pipermail/cmake/2010-May/037159.html
####################################################################################
# - Try to find Mysql-Connector-C++
# Once done, this will define
#
#  MYSQLCONNECTORCPP_FOUND - system has Mysql-Connector-C++ installed
#  MYSQLCONNECTORCPP_INCLUDE_DIRS - the Mysql-Connector-C++ include directories
#  MYSQLCONNECTORCPP_LIBRARIES - link these to use Mysql-Connector-C++
#
# The user may wish to set, in the CMake GUI or otherwise, this variable:
#  MYSQLCONNECTORCPP_ROOT_DIR - path to start searching for the module

set(MYSQLCONNECTORCPP_ROOT_DIR
        "${MYSQLCONNECTORCPP_ROOT_DIR}"
        CACHE
        PATH
        "Where to start looking for this component.")

if(WIN32)
    find_path(MYSQLCONNECTORCPP_INCLUDE_DIR
            NAMES
            mysql_connection.h
            PATHS
            "C:\\Program Files"
            HINTS
            ${MYSQLCONNECTORCPP_ROOT_DIR}
            PATH_SUFFIXES
            include)

    find_library(MYSQLCONNECTORCPP_LIBRARY
            NAMES
            mysqlcppconn
            mysqlcppconn-static
            HINTS
            ${MYSQLCONNECTORCPP_ROOT_DIR}
            PATH_SUFFIXES
            lib)

else()
    find_path(MYSQLCONNECTORCPP_INCLUDE_DIR
            mysql_connection.h
            HINTS
            ${MYSQLCONNECTORCPP_ROOT_DIR}
            PATH_SUFFIXES
            include)

    find_library(MYSQLCONNECTORCPP_LIBRARY
            NAMES
            mysqlcppconn
            mysqlcppconn-static
            HINTS
            ${MYSQLCONNECTORCPP_ROOT_DIR}
            PATH_SUFFIXES
            lib64
            lib)
endif()

mark_as_advanced(MYSQLCONNECTORCPP_INCLUDE_DIR MYSQLCONNECTORCPP_LIBRARY)

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(MysqlConnectorCpp
        DEFAULT_MSG
        MYSQLCONNECTORCPP_INCLUDE_DIR
        MYSQLCONNECTORCPP_LIBRARY)

if(MYSQLCONNECTORCPP_FOUND)
    set(MYSQLCONNECTORCPP_INCLUDE_DIRS "${MYSQLCONNECTORCPP_INCLUDE_DIR}") # Add any dependencies here
    set(MYSQLCONNECTORCPP_LIBRARIES "${MYSQLCONNECTORCPP_LIBRARY}") # Add any dependencies here
    mark_as_advanced(MYSQLCONNECTORCPP_ROOT_DIR)
endif()
#########################################################################################

set(SOURCE_FILES main.cpp)
add_executable(MySQLTEST ${SOURCE_FILES} )
target_link_libraries(MySQLTEST  ${MYSQLCONNECTORCPP_LIBRARY})

5. Compile the program with CMake

Within the same folder, type in

$ cmake .
$ make

You can just run the program by typing

$ ./MySQLTEST

If everything is running smoothly, the output result will be

Started
Successfully ended

6. Checking the result

We are going to check whether the data is successfully inserted into the table. In terminal, type in the below command followed by the ‘root’ password of MySQL server to login to the server.

 $ mysql -u root -p

Now we will type in MySQL command to see the data from the table.

mysql> SHOW DATABASES;
mysql> USE test_db;
mysql> SHOW TABLES;
mysql> SELECT * FROM test;

After the last command, the inserted data will be shown like the following table.

+------+-------+
| id   | label |
+------+-------+
|    1 | a     |
+------+-------+
1 row in set (0.00 sec)
6.1 Extra Information

I will explain about MySQL command that we just used.

Note: Remember. We need to login to the server before we use these commands. Notice that sign change from $ to mysql>

To see all the databases on the server

mysql> SHOW DATABASES;

To use/switch to a particular database

mysql> USE your_database_name;

To see all the tables on a database

mysql> SHOW TABLES;

To see all the data from a table

mysql> SELECT * FROM your_table_name;

Note: It is generally a good idea to use All Caps on MySQL command so that you will not confuse the syntax between the actual MySQL command and the data/variables;

7. Reference Links


No comments:

Post a Comment