7. Database MySQL

This article introduces the installation and configuration process of the database mysql, and calls the database through VsCode to realize some functions

1. Installation

If it was installed before, or the installation failed. Clear MySQL cache and reinstall: Run the following command to clear all MySQL cache files, and reinstall them

sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
sudo rm -rf /var/lib/mysql
sudo rm -rf /etc/mysql
sudo dpkg --configure -a
sudo apt-get update
sudo apt-get install mysql-server-5.7

Next configure mysql to allow remote connections.
By default, MySQL only allows local login. If you want to enable remote connection, you need to modify the MySQL configuration file

1. Modify the mysqld.cnf configuration file

sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf

After opening, modify the bind-address address to 0.0.0.0
insert image description here
and restart

sudo /etc/init.d/mysql restart

2. Create a remote login user

mysql -u root -p
show databases;
use mysql;
show tables;
select Host,User from user where User='root';

insert image description here
Create an admin user and specify that the user can connect to the MySQL database server from any host (% stands for wildcard, meaning all hosts)

create user 'admin'@'%' identified by '123456';
select Host,User from user;

insert image description here

3. Grant permissions to users who need to log in remotely

Computers that allow any ip address (% means that any ip address is allowed) use the admin account and password (123456) to access the mysql server.

grant all privileges on *.* to 'admin'@'%';

Two, use

Install MySQLWorkbench, you can operate the database through SQL

create database MING_DB;  #创建数据库
# drop database MING_DB;	#删除数据库
show databases;
use MING_DB;	#使用数据库
create table TBL_USER(	#创建TBL_USER表
U_ID int primary key auto_increment,
U_NAME varchar(32),
U_GENDER	varchar(32)
);
show tables;	#使用table

insert image description here

three,

In order to use the database through tools such as vscode, you need to install the mysql development tool

sudo apt-get install libmysqlclient-dev

Next, implement data insertion, query, deletion, and storage of data.
Note that for deletion, mysql generally only allows deletion of primary keys, that is, delete from TBL_USER where U_ID='2';
if you want to delete other labels, you can use a stored procedure.

#sql
DELIMITER $$
create procedure PROC_DELETE_USER(in UNAME varchar(32))
BEGIN
set sql_safe_updates=0;
delete from TBL_USER where U_NAME=UNAME;
set sql_safe_updates=1;
END$$
CALL PROC_DELETE_USER('qin');

This MySQL code defines a stored procedure named PROC_DELETE_USER, which receives a parameter UNAME that specifies the username of the user to be deleted. This stored procedure does the following:

  • Set SQL Safe Updates to 0 to allow unsafe DELETE operations.
  • Delete the records whose U_NAME field value is equal to the UNAME parameter passed to the stored procedure in the TBL_USER table.
  • Set SQL Security Updates back to 1 to disable execution of unsafe SQL statements.
  • The last line of code calls the stored procedure and passes it the string 'qin' as a parameter. In other words, this code will delete the record whose U_NAME field value is 'qin' in the TBL_USER table.

The final compilation instruction is to gcc -o mysql mysql.c -I/usr/include/mysql/ -lmysqlclient
first look at the key functions

  • MYSQL mysql: Define a structure variable of MYSQL type, initialize it by calling the mysql_init() function, and call the mysql_error() function to get the error information
  • mysql_real_connect(): used to connect to the MySQL server, returns 0, unsuccessful. It requires the following parameters:
    1. A pointer to a structure of type MYSQL, which has been initialized by mysql_init().
    2. The host name or IP address of the MySQL server.
    3. The user name used when logging in to the MySQL server.
    4. The password used when logging in to the MySQL server.
    5. The name of the database to be connected.
    6. Port number (3306 by default).
    7. Specify socket 8. Specify different connection options
  • mysql_real_query(): used to send SQL query or update statement to MySQL server, return non-0, indicating unsuccessful. It requires the following parameters:
    1. A pointer to a structure of type MYSQL, which has been initialized by mysql_init().
    2. The SQL query or update statement to be executed.
    3. The length of the SQL query or update statement (if it is 0, it will be calculated automatically).
  • MYSQL_RES *res=mysql_store_result(&mysql): Used to retrieve all result sets from the previous query. When you retrieve data from the database using a SELECT statement, the results are returned to the client and stored in a MYSQL_RES structure. Use mysql_store_result(): The function stores the entire result set in memory and returns a MYSQL_RES* pointer pointing to this result set. This allows us to easily iterate over and manipulate the result set.
  • int rows=mysql_num_rows(res) is used to obtain the number of rows in the query result set.
  • mysql_fetch_row(): Used to get the next row of data from the query result set.
  • int rows=mysql_num_rows(res): Used to get the number of rows in the query result set
  • mysql_fetch_row(): Used to get the next row of data from the query result set
#include<stdio.h>
#include<string.h>
#include <mysql.h>

#define MING_DB_IP           "192.168.42.128"
#define MING_DB_PORT         3306
#define MING_DB_USENAME      "admin"
#define MING_DB_PASSWORD     "123456"
#define MING_DB_DEFAULTDB    "MING_DB"

#define SQL_INSERT_TRL_USER     "insert TBL_USER(U_NAME,U_GENDER) values('zxm','women');"
#define SQL_SELECT_TBL_USER     "select * from TBL_USER;"
#define SQL_DELETE_TBL_USER     "CALL PROC_DELETE_USER('zxm')"
//查询
int ming_mysql_select(MYSQL *handle){
    
    
    //发送sql语句-->select
    if(mysql_real_query(handle,SQL_SELECT_TBL_USER,strlen(SQL_SELECT_TBL_USER))){
    
    
        //不等于0,不成功
        printf("mysql_real_query:%s\n",mysql_error(handle));
        return -1;
    }

    //存储结果
        //mysql_store_result()用于从上一次查询中检索所有结果集
    MYSQL_RES *res=mysql_store_result(handle);
    if (res==NULL){
    
    
        printf("mysql_store_result:%s\n",mysql_error(handle));
        return -2;
    }

    //判断结果行数和列数
        //mysql_num_rows()用于获取查询结果集中行的数量
    int rows=mysql_num_rows(res);
    printf("rows:%d\n",rows);

    int fields=mysql_num_fields(res);
    printf("fields:%d\n",fields);

    //抓取数据
    MYSQL_ROW row;
        //mysql_fetch_row()用于从查询结果集中获取下一行数据
    while ((row=mysql_fetch_row(res))){
    
    
        int i=0;
        for (i=0;i<fields;i++){
    
    
            printf("%s\t",row[i]);
        }
        printf("\n");
    }


    mysql_free_result(res);

    return 0;
}

int main(){
    
    

    //定义一个MYSQL类型的结构体变量,并通过调用mysql_init()函数对其进行初始化
    //调用mysql_error()函数来获取有关错误信息
     MYSQL mysql;
    
    if (mysql_init(&mysql)==NULL){
    
    
        printf("mysql_init:%s\n",mysql_error(&mysql));
        return -1;
    }

    //mysql_real_connect()用于连接到MySQL服务器.它需要以下参数:
    /*1、MYSQL类型的结构体指针,该结构体已由mysql_init()初始化。
      2、MySQL服务器所在主机名或IP地址。
      3、登录MySQL服务器时使用的用户名。
      4、登录MySQL服务器时使用的密码。
      5、要连接的数据库名称。
      6、端口号(默认为3306)。
      7、规定 socket    8、规定不同的连接选项
    */
    if(!mysql_real_connect(&mysql,MING_DB_IP,MING_DB_USENAME,MING_DB_PASSWORD,
    MING_DB_DEFAULTDB,MING_DB_PORT,NULL,0)){
    
        //等于0,不成功
        printf("mysql_real_connect:%s\n",mysql_error(&mysql));
        return -2;
    }


    printf("case:mysql insert \n");
#if 1
    /*mysql_real_query()用于向MySQL服务器发送SQL查询或更新语句。它需要以下参数:
      1、MYSQL类型的结构体指针,该结构体已由mysql_init()初始化。
      2、要执行的SQL查询或更新语句。
      3、SQL查询或更新语句的长度(如果为0,则将自动计算)。
    */
    if(mysql_real_query(&mysql,SQL_INSERT_TRL_USER,strlen(SQL_INSERT_TRL_USER))){
    
    
        //不等于0,不成功
        printf("mysql_real_query:%s\n",mysql_error(&mysql));
        return -3;
    }

#endif

    //输出表的结果
    ming_mysql_select(&mysql);

    printf("case:mysql delete \n");
#if 1
    /*mysql_real_query()用于向MySQL服务器发送SQL查询或更新语句。它需要以下参数:
      1、MYSQL类型的结构体指针,该结构体已由mysql_init()初始化。
      2、要执行的SQL查询或更新语句。
      3、SQL查询或更新语句的长度(如果为0,则将自动计算)。
    */
    if(mysql_real_query(&mysql,SQL_DELETE_TBL_USER,strlen(SQL_DELETE_TBL_USER))){
    
    
        //不等于0,不成功
        printf("mysql_real_query:%s\n",mysql_error(&mysql));
        return -3;
    }

#endif

    //输出表的结果
    ming_mysql_select(&mysql);

    //关闭
    mysql_close(&mysql);

    return 0;

}

Guess you like

Origin blog.csdn.net/Ricardo2/article/details/130810347