C语言操作MySQL步骤

友情提示:朋友毕设让帮忙写写伪代码,并不是系统学习,只列取最基本和最常用的API,及其例程。

连接

C语言连接MySQL包含两步:

  • 初始化一个连接句柄
  • 实际进行连接
    MYSQL *mysql_init(MYSQL *);
    //参数含义可查
    MYSQL *mysql_real_connect(MYSQL *connection,
                              const char *server_host,
                              const char *sql_user_name,
                              const char *sql_password,
                              const char *db_name,
                              unsigned int port_number,
                              const char *unix_socket_name,
                              unsigned int flags);

Ex:

MYSQL *conn_ptr;

conn_ptr = mysql_init(NULL);
if(!conn_ptr)
{
    ...//mysql_init failed
}
conn_ptr = mysql_real_connect(conn_ptr, "localhost", "rick", "secret", "foo", 0, NULL, 0);
if(conn_ptr)
{
    ...//connection success
}
else
{
    ...//connection failed
}

错误处理

  • char *mysql_error(MYSQL *connection);
  • unsigned int mysql_errno(MYSQL *connection);

Ex:

MYSQL *conn_ptr;

conn_ptr = mysql_init(NULL);
if(!conn_ptr)
{
    ...//mysql_init failed
}
conn_ptr = mysql_real_connect(conn_ptr, "localhost", "rick", "secret", "foo", 0, NULL, 0);
if(conn_ptr)
{
    ...//connection success
}
else
{
    if(mysql_errno(conn_ptr))
    {
        fprintf(stderr, "Connection error %d: %s\n",mysql_errno(conn_ptr), mysql_error(conn_ptr));
    }
}

执行SQL语句

执行sql语句的主要API函数为:

//传入连接名和sql语句,成功返回0
int mysql_query(MYSQL *connection, const char *query)

对sql语句的执行结果有两种情况:

  • 不返回数据(UPDATEDELETEINSERT
  • 返回数据(SELECT

不返回数据

这种情况较为简单,基本是只看成功与不成功

Ex:

MYSQL *conn_ptr;
...//初始化,连接数据库(省略)

res = mysql_query(conn_ptr, "INSERT INTO ... VALUES(...)");
if(!res)
{
    ...//success
}
else
{
    ...//error
}

返回数据的语句

一般需要四个步骤:

  • 执行查询(mysql_query)
  • 提取数据(mysql_use_result;mysql_store_result)
  • 处理数据(mysql_fetch_row)
  • 必要的清理工作(mysql_free_result)

执行查询

//传入连接名和sql语句,成功返回0
int mysql_query(MYSQL *connection, const char *query)

提取数据

有两种提取数据函数:

  • mysql_store_result(一次返回所有结果)
  • mysql_use_result(一次返回一行数据)

在贴代码之前,还需要知道一个函数:mysql_fetch_row

//从mysql_store_result的结果中提取一行
MYSQL_ROW mysql_fetch_row(MYSQL_RES *result);

Ex:(mysql_store_result)

MYSQL *conn_ptr;
MYSQL_RES *res_ptr;
MYSQL_ROW sqlrow;

...//初始化,连接数据库(省略)

res = mysql_query(conn_ptr, "SELECT ... FROM...");
if(res)
{
    ...//error
}
else
{
    res_ptr = mysql_store_result(conn_ptr);
    if(res_ptr)
    {
        while((sqlrow = mysql_fetch_row(res_ptr)))
        {
            ...
        }
    }
    mysql_free_result(res_ptr);
}
mysql_close(conn_ptr);

处理数据

MySQL返回两种类型的数据:

  • 从表中提取的信息,即列数据
  • 数据的数据,即元数据,例如列名和类型等

mysql_field_count函数提供了一些关于查询结果的基本信息

Ex:

MYSQL *conn_ptr;
MYSQL_RES *res_ptr;
MYSQL_ROW sqlrow;   
unsigned int field_count=0;

//初始化、连接、得到结果集(省略)

while((sqlrow = mysql_fetch_row(res_ptr)))
{
    while(field_count < mysql_field_count(conn_ptr))
    {
        printf("%s ", sqlrow[field_count]);
        field_count++;
    }
}

清理

  • 关闭连接(mysql_close)
  • 清内存(mysql_free_result)

API:

void mysql_close(MYSQL *connection);
void mysql_free_result(MYSQL_RES *result);

例程

贴一个完整的代码:

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

#include "mysql.h"

MYSQL my_connection;
MYSQL_RES *res_ptr;
MYSQL_ROW sqlrow;

void display_header();
void display_row();


int main(int argc, char *argv[]) {
   int res;
   int first_row = 1; /* Used to ensure we display the row header exactly once when data is successfully retrieved */


   mysql_init(&my_connection);  
   if (mysql_real_connect(&my_connection, "localhost", "rick", 
                                                "secret", "foo", 0, NULL, 0)) {
      printf("Connection success\n");
   
      res = mysql_query(&my_connection, "SELECT childno, fname, age FROM children WHERE age > 5");

      if (res) {
         fprintf(stderr, "SELECT error: %s\n", mysql_error(&my_connection));
      } else {
         res_ptr = mysql_use_result(&my_connection);
         if (res_ptr) {
            while ((sqlrow = mysql_fetch_row(res_ptr))) {
               if (first_row) {
                  display_header();
                  first_row = 0;
               }
               display_row();
            }
            if (mysql_errno(&my_connection)) {
             fprintf(stderr, "Retrive error: %s\n",
                                mysql_error(&my_connection));
            }
            mysql_free_result(res_ptr);
         }
      }
      mysql_close(&my_connection);
   } else {
      fprintf(stderr, "Connection failed\n");
      if (mysql_errno(&my_connection)) {
        fprintf(stderr, "Connection error %d: %s\n",
                                mysql_errno(&my_connection),
                                mysql_error(&my_connection));
        }
      }
   
   return EXIT_SUCCESS;
}


void display_header() {
   MYSQL_FIELD *field_ptr;

   printf("Column details:\n");
 
   while ((field_ptr = mysql_fetch_field(res_ptr)) != NULL) {
      printf("\t Name: %s\n", field_ptr->name);
      printf("\t Type: ");
      if (IS_NUM(field_ptr->type)) {
         printf("Numeric field\n");
      } else {
         switch(field_ptr->type) {
            case FIELD_TYPE_VAR_STRING:
               printf("VARCHAR\n");
            break;
            case FIELD_TYPE_LONG: 
               printf("LONG\n");
            break;
            default:
              printf("Type is %d, check in mysql_com.h\n", field_ptr->type);
         } /* switch */
      } /* else */

      printf("\t Max width %ld\n", field_ptr->length); /* Note on versions of MySQL before 4.0 the format should be %d, rather than %ld */
      if (field_ptr->flags & AUTO_INCREMENT_FLAG) 
         printf("\t Auto increments\n");
      printf("\n");
   } /* while */
}


void display_row() {
   unsigned int field_count;

   field_count = 0;
   while (field_count < mysql_field_count(&my_connection)) {
      if (sqlrow[field_count]) printf("%s ", sqlrow[field_count]);
      else printf("NULL");
      field_count++;
   }
   printf("\n");
}
    原文作者:Dufre
    原文地址: https://www.jianshu.com/p/5b80aa05199a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞