ubuntu uses mysql and connects it to C + + programs

Install mysql

sudo apt-get install mysql-server
sudo apt-get install mysql-client
sudo apt-get install libmysqlclient-dev

During the installation process, you will be prompted to set a password, so that you can complete the mysql installation. You can log in through the following command:

mysql -u root -p where - u represents the user name of login - p represents the database of login```

Some methods to create and modify the database at the terminal: Use database
matters needing attention:
1. When creating a database, remember to select the encoding method of the string, usually utf8
2. Once the database is established, its coding mode is difficult to change. Do not try to modify the / etc/mysql/my.con file, which will cause the database to fail to start, so I am trapped here, It's very clear here

Install workbench visual interface management database

sudo apt-get install mysql-workbench

How to manage and use Baidu.

Link to C + + Project

First, you need to install a link library:

sudo apt-get install libmysqlcppconn-dev

The CMakeLists.txt file is organized as follows: (note that target? Link? Libraries has two links)

cmake_minimum_required(VERSION 3.5)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES main.cpp)
add_executable(database_test ${SOURCE_FILES})
target_link_libraries(database_test mysqlcppconn-static mysqlclient)

main.cpp file:

#include <stdlib.h>
#include <iostream>
#include "mysql_connection.h"
//#include <mysql_driver.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
using namespace std;
int main() {
    sql::Driver *driver;
    sql::Connection *con;
    sql::Statement *stmt;
    sql::ResultSet *res;
    sql::PreparedStatement *pstmt;
    /* create a connection */
    driver = get_driver_instance();
    con = driver->connect("tcp://", "xky", "123456");
    stmt = con->createStatement();
    res = stmt->executeQuery("select * from unit");
    while (res->next())
        cout << "id = " << res->getInt("id") << " ";
        cout << "name = " << res->getString("unit_name")<<endl;
    cout << endl;
    delete stmt;
    stmt = con->createStatement();
    stmt->execute("drop table if exists test_id");
    stmt->execute("create table test_id(id INT)");
    delete stmt;
    pstmt = con->prepareStatement("insert into test_id(id) values(?)");
    for(int i = 0; i < 10; i++)
        pstmt->setInt(1, i);
    delete pstmt;
    pstmt = con->prepareStatement("select id from test_id order by id ASC");
    res = pstmt->executeQuery();
//    res->afterLast();
        cout << "\t... MySQL counts: " << res->getInt("id") << endl;
    delete res;
    delete pstmt;
    delete con;
    return EXIT_SUCCESS;

For more information, see Official website

Tags: MySQL Database sudo SQL

Posted on Tue, 05 May 2020 10:27:51 -0700 by mrneilrobinson