Use C++ to connect to the database and implement related operations

Today, I want to learn how to connect MySQL with C++ under Linux and implement some simple operations. I have stepped on a lot of pits.
The first is the mysql environment problem, which can be used before, and suddenly an error is reported:
Can't connect to local MySQL server through socket'/var/run/mysqld/mysqld.sock' (2)"

Then I searched a lot of answers on the Internet, including changing the configuration file, downloading and updating mysql-client, mysql-server, mysql-dev, etc., but I didn’t get any results after a long time. I just deleted mysql and reinstalled in a hurry. You can see for details. How cool to delete mysql , I hope some big guys can tell me what the reason is. Orz found it, and it's dry, because I didn't start the mysql service (- _-) when I just started it. I saw this error solution before I knew it.

One thing to say, it’s really cool, and then reinstall, you can go to the Internet to search the link for the installation, there are not too many bugs.

Then enter the topic, if you want to use C++ to operate the database, you can first create the database and table in mysql, otherwise it will not be connected. The table I built here
Insert picture description here
looks like this: Then I import the mysql/mysql.h header file in C++ and use the functions inside to access the database. After writing the code, directly compiling with g++ will report an error:
mysql.h: No such file or directory

This error occurs because the system does not have the mysql development library installed.
Execute the following command to install
sudo apt-get install libmysql+±dev. When
compiling, you need to add the connection -lmysqlclient.
The time to compile the source code is as follows:
* gcc -I/usr/include/mysql .c -L/usr/lib/mysql -lmysqlclient -o *
That is to add the library path and library, the library path search can be seen: view the mysql library path

The source code is as follows:

#include <iostream>
#include <string>
#include <mysql/mysql.h>
using namespace std;

class MysqlDB {
    
    
private:
    MYSQL mysql;
    MYSQL_ROW row;
    MYSQL_RES *result;
    MYSQL_FIELD *field;
public:
    MysqlDB() 
    {
    
    
        if( mysql_init( &mysql ) == NULL ) 
        {
    
    
            cout << "init error, line: " << __LINE__ << endl;
            exit(-1);
        }
    }
    
    ~MysqlDB() 
    {
    
    
        mysql_close( &mysql );
    }
    
    void connect( string host, string user, string passwd,  string database ) 
    {
    
    
        if( !mysql_real_connect( &mysql, host.c_str(), user.c_str(), passwd.c_str(), database.c_str(), 0, NULL, 0 ) ) 
        {
    
    
            cout << "connect error, line: " << __LINE__ << endl;
            exit(-1);
        }
    }
    
    void add();
    void print();
};

void MysqlDB::add() 
{
    
    
    string id, name, sex, birthday;
    do {
    
    
        cout << "请输入学生信息:\n";

        cin >> id >> name >> sex >> birthday;
        string sql = "insert into info values('" + id + "', '" + name + 
                        "', '" + sex + "', '" + birthday + "');";

        mysql_query( &mysql, sql.c_str() );
        cout << "是否继续(y/n): ";
        cin >> id;
    } while( id == "y" );
}

void MysqlDB::print() 
{
    
    

    // string sql = "select * from info where name = '" + name + "';";  //要有''
    string sql = "select * from info;";
    mysql_query( &mysql, sql.c_str() );

    result = mysql_store_result( &mysql );
    if( !result ) 
    {
    
    
        cout << "result error, line : " << __LINE__ << endl;
        return ;
    }

    int num = mysql_num_fields( result );  //返回字段个数
    for( int i = 0; i < num; i++ ) {
    
    
        field = mysql_fetch_field_direct( result, i );  //返回字段类型
        cout << field->name << "\t\t";  //输出字段名
    }
    cout << endl;

    while( row = mysql_fetch_row( result ), row ) 
    {
    
    
        for( int i = 0; i < num; i++ ) 
        {
    
    
            cout << row[i] << "\t\t";
        }
        cout << endl;
    }
}

int main() 
{
    
    
    MysqlDB db;
    db.connect( "localhost", "root", "root用户密码", "student" ); 

    db.print();
    db.add();
    db.print();

    return 0;
}

Because I need a password, I also tried to find a way to find the root password. There are many ways on the Internet. I will list one to check the mysql user password.
Run results:
Insert picture description here
check in the database:
Insert picture description here

Blog link: Use C++ to operate mysql under linux

mysql official C API library see C API for mysql

Database related statements can be seen in the rookie tutorial-mysql statement

Guess you like

Origin blog.csdn.net/weixin_45146520/article/details/109165849