Bootstrap

c API【MySQL】

C语言连接MySQL

mysql_get_client_info来判断库是否引入成功,该函数的作用就是获取客户端的版本信息

#include<iostream>
#include<mysql/mysql.h>

int main()
{
    std::cout<<"mysql client version :" <<mysql_get_client_info()<<std::endl;
    
    return 0 ;

}

MySQL API

mysql_real_connect ,连接数据库

MYSQL* mysql_real_connect(MYSQL *mysql, const char *host,
					const char *user,
					const char *passwd,
					const char *db,
					unsigned int port,
					const char *unix_socket,
					unsigned long clientflag);

  • 参数说明:

mysql: 表示在连接数据库前,调用mysql_init函数创建的MySQL对象。
host: 表示需要连接的MySQL服务器的IP地址,"127.0.0.1"表示连接本地MySQL服务器。
user: 表示连接MySQL服务器时,所使用用户的用户名。
passwd: 表示连接MySQL服务器时,所使用用户的密码
db: 表示连接MySQL服务器后,需要使用的数据库。
port: 表示连接的MySQL服务器,所对应的端口号。
unix_socket: 表示连接时应该使用的套接字或命名管道,通常设置为NULL。
clientflag: 可以设置为多个标志位的组合,表示允许特定的功能,通常设置为0。

  • 返回值说明:

如果连接数据库成功,则返回一个MySQL对象,该对象与第一个参数的值相同。
如果连接数据库失败,则返回NUL

#include<iostream>
#include<mysql/mysql.h>

const std::string host = "localhost" ;
const std::string user = "zhangsan" ;
const std::string password = "123456" ;
const std::string db = "conn" ;
const unsigned int port = 8080;

int main()
{
  
    MYSQL * my = mysql_init(nullptr) ;
    
    if(my==nullptr)
    {
        std::cerr<<"init MySQL error" <<std::endl;
        return 1 ;
    }
    if(  mysql_real_connect(my,host.c_str() , user.c_str() ,password.c_str() ,db.c_str() ,port, nullptr,0) ==nullptr    )
    {
          std::cerr<<"Connect  error" <<std::endl;
        return 2 ;
    }
            std::cout<<"Connect  success" <<std::endl;

    mysql_close(my) ;
    return 0 ;

}

show processlist 显示当前在 MySQL 服务器上运行的所有线程(进程)的列表

mysql> show processlist;
+----+-----------+-----------------+------+---------+------+----------+------------------+
| Id | User      | Host            | db   | Command | Time | State    | Info             |
+----+-----------+-----------------+------+---------+------+----------+------------------+
| 43 | connector | localhost:46848 | conn | Query   |    0 | starting | show processlist |
+----+-----------+-----------------+------+---------+------+----------+------------------+
1 row in set (0.00 sec)

mysql_query ,与数据库建立连接期间,就可以向MySQL服务器下发SQL请求,下发SQL请求

int	mysql_query(MYSQL *mysql, const char *q);

参数说明:

  • mysql: 表示在连接数据库前,调用mysql_init函数创建的MySQL对象。
  • q: 表示向MySQL服务器下发的SQL请求,SQL最后可以不带分号。

返回值说明:

  • 返回值为0表示SQL执行成功,否则表示SQL执行失败
#include<iostream>
#include<mysql/mysql.h>

const std::string host = "localhost" ;
const std::string user = "zhangsan" ;
const std::string password = "123456" ;
const std::string db = "conn" ;
const unsigned int port = 8080;

int main()
{
    
    MYSQL * my = mysql_init(nullptr) ;
    
    if(my==nullptr)
    {
        std::cerr<<"init MySQL error" <<std::endl;
        return 1 ;
    }
    if(  mysql_real_connect(my,host.c_str() , user.c_str() ,password.c_str() ,db.c_str() ,port, nullptr,0) ==nullptr    )
    {
          std::cerr<<"Connect MySQL  error" <<std::endl;
        return 2 ;
    }
          


        std::string sql;
      while(true)
      {
        
        
           std::cout<<"MySQL >>> " ;
           //获取失败
           if(!std::getline ( std::cin ,sql ) )
           {    
                 std::cout<< "bye bye "<<std::endl;
                break;
           }
            if(sql=="quit")
            {
                 std::cout<< "bye bye "<<std::endl;
                break;
            }
          int n = mysql_query(my ,sql.c_str());
          if(n==0)
          {
                std::cout<<sql<<"success : "<<n<<std::endl;
          }
          else
          {
                 std::cerr<<sql<<"failed : "<<n<<std::endl;
          }

      }

//   std::cout<<"Connect  success" <<std::endl;

    mysql_close(my) ;
    return 0 ;

}

在这里插入图片描述

mysql_set_character_set ,在连接数据库之后,需要统一客户端和服务器的编码格式,避免在数据交互过程中出现乱码,设置编码格式

int mysql_set_character_set(MYSQL *mysql, const char *csname);

参数说明:

  • mysql: 表示在连接数据库前,调用mysql_init函数创建的MySQL对象。
  • csname: 表示要设置的编码格式,如"utf8"

返回值说明:

  • 返回值为0表示设置成功,否则表示设置失败

测试

#include<iostream>
#include<mysql/mysql.h>

const std::string host = "localhost" ;
const std::string user = "zhangsan" ;
const std::string password = "123456" ;
const std::string db = "conn" ;
const unsigned int port =8080;

int main()
{
    
    MYSQL * my = mysql_init(nullptr) ;
    
    if(my==nullptr)
    {
        std::cerr<<"init MySQL error" <<std::endl;
        return 1 ;
    }
    if(  mysql_real_connect(my,host.c_str() , user.c_str() ,password.c_str() ,db.c_str() ,port, nullptr,0) ==nullptr    )
    {
          std::cerr<<"Connect MySQL  error" <<std::endl;
        return 2 ;
    }
          

       mysql_set_character_set(my,"utf8"); //防止mysql客户端解析数据时出现乱码




        std::string sql="insert into user (name,age,telphone) values('wangwu' , 20,'5556566')";
        
         int n = mysql_query(my,sql.c_str());
         if(n==0) std::cout<<sql<<"success" <<std::endl;
         else    std::cout<<sql<<"failed " <<std::endl;



    mysql_close(my) ;
    return 0 ;

}

c/c++查询需要注意的细节

MYSQL_RES* mysql_store_result(MYSQL *mysql);

说明一下:

  • 该函数会调用指定MySQL对象中对应的函数指针来获取查询结果,并将获取到的查询结果保存到MYSQL_RES变量中进行返回。
  • 需要注意的是,MYSQL_RES变量的内存空间是malloc出来的,因此在使用完后需要调用free函数进行释放,否则会造成内存泄露

MYSQL_RES变量中保存了查询得到的各种信息:

typedef struct st_mysql_res {
  my_ulonglong  row_count;
  MYSQL_FIELD	*fields;
  MYSQL_DATA	*data;
  MYSQL_ROWS	*data_cursor;
  unsigned long *lengths;		/* column lengths of current row */
  MYSQL		*handle;		/* for unbuffered reads */
  const struct st_mysql_methods *methods;
  MYSQL_ROW	row;			/* If unbuffered read */
  MYSQL_ROW	current_row;		/* buffer to current row */
  MEM_ROOT	field_alloc;
  unsigned int	field_count, current_field;
  my_bool	eof;			/* Used by mysql_fetch_row */
  /* mysql_stmt_close() had to cancel this result */
  my_bool       unbuffered_fetch_cancelled;  
  void *extension;
} MYSQL_RES;

mysql_num_rows ,获取查询结果的行数

my_ulonglong mysql_num_rows(MYSQL_RES *res);
  • 该函数将会从指定的MYSQL_RES对象中,获取查询结果的行数

mysql_num_fields , 获取查询结果的列数

unsigned int mysql_num_fields(MYSQL_RES *res);
  • 该函数将会从指定的MYSQL_RES对象中,获取查询结果的列数
MYSQL_ROW mysql_fetch_row(MYSQL_RES *result);
  • 该函数将会从指定的MYSQL_RES对象中,获取查询结果中的一行数据

MYSQL_ROW对象中保存着一行数据,这一行数据中可能包含多个字符串,对应就是这行数据中的多个列信息,因此MYSQL_ROW本质就是char**类型,其类型定义如下

typedef char **MYSQL_ROW;		/* return data as array of strings */

测试代码

#include <iostream>
#include <mysql/mysql.h>

const std::string host = "localhost";
const std::string user = "zhangsan";
const std::string password = "123456";
const std::string db = "conn";
const unsigned int port =8080;

int main()
{

    MYSQL *my = mysql_init(nullptr);

    if (my == nullptr)
    {
        std::cerr << "init MySQL error" << std::endl;
        return 1;
    }
    if (mysql_real_connect(my, host.c_str(), user.c_str(), password.c_str(), db.c_str(), port, nullptr, 0) == nullptr)
    {
        std::cerr << "Connect MySQL  error" << std::endl;
        return 2;
    }

    //   mysql_set_character_set(my,"utf8"); //防止mysql客户端解析数据时出现乱码

    // std::string sql="insert into user (name,age,telphone) values('wangwu' , 20,'5556566')";
    std::string sql = "select * from user";
    int n = mysql_query(my, sql.c_str());
    if (n == 0)
        std::cout << sql << "success" << std::endl;
    else
    {
        std::cerr << sql << "failed " << std::endl;
        return 3;
    }
    MYSQL_RES *res = mysql_store_result(my);
    if (nullptr == res)
    {
        std::cerr << "mysql_store_result failed " << std::endl;
        return 4 ;
    }
                         my_ulonglong rows   =mysql_num_rows(res);
                           my_ulonglong fields   =mysql_num_fields(res);

                 std::cout <<  "行:" <<  rows<< std::endl;
                     std::cout << "列:" << fields<< std::endl;

     //遍历行列
     for( int i = 0 ;  i< rows ; i++)
     {
                    MYSQL_ROW row  = mysql_fetch_row(res) ;
        for ( int j =0 ; j <fields  ; j++)
        {
                std::cout<<row[j] <<"\t" ;
        }
          std::cout<<"\n" ;
     }

    mysql_close(my);
    return 0;
}

在这里插入图片描述

mysql_fetch_fields ,获取查询结果的列属性

MYSQL_FIELD* mysql_fetch_fields(MYSQL_RES *res);
  • 该函数将会从指定的MYSQL_RES对象中,获取查询结果的列属性

mysql_fetch_fields函数将会返回多个MYSQL_FIELD对象,每个MYSQL_FIELD对象中保存着对应列的各种列属性

typedef struct st_mysql_field {
	char *name;                 /* Name of column */
	char *org_name;             /* Original column name, if an alias */
	char *table;                /* Table of column if column was a field */
	char *org_table;            /* Org table name, if table was an alias */
	char *db;                   /* Database for table */
	char *catalog;	      /* Catalog for table */
	char *def;                  /* Default value (set by mysql_list_fields) */
	unsigned long length;       /* Width of column (create length) */
	unsigned long max_length;   /* Max width for selected set */
	unsigned int name_length;
	unsigned int org_name_length;
	unsigned int table_length;
	unsigned int org_table_length;
	unsigned int db_length;
	unsigned int catalog_length;
	unsigned int def_length;	
	unsigned int flags;         /* Div flags */
	unsigned int decimals;      /* Number of decimals in field */
	unsigned int charsetnr;     /* Character set */
	enum enum_field_types type; /* Type of field. See mysql_com.h for types */
	void *extension;
} MYSQL_FIELD;

#include <iostream>
#include <mysql/mysql.h>

const std::string host = "localhost";
const std::string user = "zhangsan";
const std::string password = "123456";
const std::string db = "conn";
const unsigned int port = 8080;

int main()
{

    MYSQL *my = mysql_init(nullptr);

    if (my == nullptr)
    {
        std::cerr << "init MySQL error" << std::endl;
        return 1;
    }
    if (mysql_real_connect(my, host.c_str(), user.c_str(), password.c_str(), db.c_str(), port, nullptr, 0) == nullptr)
    {
        std::cerr << "Connect MySQL  error" << std::endl;
        return 2;
    }

    //   mysql_set_character_set(my,"utf8"); //防止mysql客户端解析数据时出现乱码

    // std::string sql="insert into user (name,age,telphone) values('wangwu' , 20,'5556566')";
    std::string sql = "select * from user";
    int n = mysql_query(my, sql.c_str());
    if (n == 0)
        std::cout << sql << "success" << std::endl;
    else
    {
        std::cerr << sql << "failed " << std::endl;
        return 3;
    }
    MYSQL_RES *res = mysql_store_result(my);
    if (nullptr == res)
    {
        std::cerr << "mysql_store_result failed " << std::endl;
        return 4 ;
    }
                         my_ulonglong rows   =mysql_num_rows(res);
                           my_ulonglong fields   =mysql_num_fields(res);

                 std::cout <<  "行:" <<  rows<< std::endl;
                     std::cout << "列:" << fields<< std::endl;

       //列属性
     MYSQL_FIELD* fields_array  =      mysql_fetch_fields(res);
        for(int i =0 ;i <  fields; i++ )
        {
                 std::cout<<fields_array[i].name <<"\t" ;
        }
          std::cout<<"\n" ;



     //遍历行列
     for( int i = 0 ;  i< rows ; i++)
     {
                    MYSQL_ROW row  = mysql_fetch_row(res) ;
        for ( int j =0 ; j <fields  ; j++)
        {
                std::cout<<row[j] <<"\t" ;
        }
          std::cout<<"\n" ;
     }





    mysql_close(my);
    return 0;
}

在这里插入图片描述

mysql_fetch_row ,获取查询结果中的一行数据

 MYSQL_ROW mysql_fetch_row(MYSQL_RES *result);
  • 该函数将会从指定的MYSQL_RES对象中,获取查询结果中的一行数据
;