Installing MySql database on ubuntu and connecting database service through C/C + + language

Keywords: MySQL Ubuntu sudo SQL

Development environment: ubuntu-17.10.1-desktop-amd64
Download link: https://www.ubuntu.com/download/desktop

1. Install mysql through apt get

sudo apt-get install mysql-server mysql-client

Note: my ubuntu-16 version can't be installed, so I can't find the corresponding website, so we can update the software source through sudo apt get update.

2. Install mysql client function library

sudo apt-get install libmysqlclient-dev -y

3. Now that the environment is installed, check whether the client function library is installed

ls /usr/include/mysql/
ls /usr/lib/mysql/

4. Write a simple example.
create_children.sql l script:

create database foo;
use foo;
create table children(
    childno int primary key,
    name varchar(20),
    age int
);
insert into children values(1,'Jenny',12);
insert into children values(2,'Tom',21);

Client program connect.c:

#include <stdlib.h>
#include <stdio.h>
#include "mysql.h"

int main(int argc,char *argv[])
{
    MYSQL *conn_ptr;
    conn_ptr = mysql_init(NULL);
    if(!conn_ptr)
    {
        fprintf(stderr,"mysql_init failed\n");
        return EXIT_FAILURE;
    }
    conn_ptr = mysql_real_connect(conn_ptr,"localhost","rick","123456","foo",0,NULL,0);
    if(conn_ptr)
    {
        printf("Connection success!\n");
    }else{
        printf("Connection failed\n");
    }
    mysql_close(conn_ptr);
    return 0;
}

5. Create a normal user for mysql server

mysql> grant all on *.* to rick@localhost identified by "123456";

6. Enter mysql server and run script

mysql -u rick -p

source create_children.sql;

7. Compile connect.c

gcc -o connect1 connect1.c -I/usr/include/mysql -L/usr/lib/mysql -lmysqlclient

Note: because the mysql.h file contained in the c program is in the / usr/include/mysql / directory.

8. Run the connect1 executable, resulting in:

Connection success!

Posted by djs1 on Sun, 05 Apr 2020 11:12:17 -0700