c 连接mysql数据库

Posted by boyli on March 18, 2021

c 连接mysql数据库

1、安装mysql-server

 root@aliyun:~# apt install mysql-server
安装完成后
 root@aliyun:~# mysql_secure_installation  //一些初始化  包括设置密码。。
 root@aliyun:~# mysql -uroot -pmysql
  
create user 'username'@'%' identified by 'password';
grant all on *.* to 'username'@'%';

2、安装MySQL database development files

root@aliyun:~# apt install mysql-client libmysqlclient-dev
root@aliyun:~# updatedb
root@aliyun:~# locate mysql.h  //定位一下
usr/include/mysql/mysql.h 

3、代码演示

/*************************************************************************
	> File Name: 1.mysql.c
	> Author:  boyli
	> Mail:  
	> Created Time: 2021-03-17 23:40:35
 ************************************************************************/

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

int main() {
    MYSQL *mysql = NULL;
    if ((mysql = mysql_init(NULL)) == NULL) {
        perror("mysql_init");
        exit(1);
    }
    mysql = mysql_real_connect(mysql, "172.25.11.182", "liyingbo", "mysql", "foo", 0, 0, 0);
    if (!mysql) {
        perror("connect failed!");
        exit(1);
    }
    printf("success!!!\n");
    return 0;
}

liyingbo@aliyun ~ % gcc 1.mysql.c -I /usr/include/mysql/ -lmysqlclient  
liyingbo@aliyun ~ % ./a.out
success!!!