>  기사  >  데이터 베이스  >  MySQL 시작하기: 하나의 함수 호출로 여러 명령문 실행

MySQL 시작하기: 하나의 함수 호출로 여러 명령문 실행

黄舟
黄舟원래의
2017-01-19 15:43:031134검색

ν 단일 문자열에 지정된 여러 문 실행을 지원합니다. 주어진 연결에서 이 기능을 사용하려면 연결을 열 때 mysql_real_connect()에 대한 flags 매개변수에 CLIENT_MULTI_STATEMENTS 옵션을 지정해야 합니다. mysql_set_server_option(MYSQL_OPTION_MULTI_STATEMENTS_ON)을 호출하여 기존 연결에 대해 설정할 수도 있습니다.

일반적인 루틴:

/* Connect to server with option CLIENT_MULTI_STATEMENTS */
mysql_real_connect(..., CLIENT_MULTI_STATEMENTS);
/* Now execute multiple queries */
mysql_query(mysql,"DROP TABLE IF EXISTS test_table;\
                   CREATE TABLE test_table(id INT);\
                   INSERT INTO test_table VALUES(10);\
                   UPDATE test_table SET id=20 WHERE id=10;\
                   SELECT * FROM test_table;\
                   DROP TABLE test_table");
do
{
  /* Process all results */
  ...
  printf("total affected rows: %lld", mysql_affected_rows(mysql));
  ...
  if (!(result= mysql_store_result(mysql)))
  {
     printf(stderr, "Got fatal error processing query\n");
     exit(1);
  }
  process_result_set(result); /* client function */
  mysql_free_result(result);
} while (!mysql_next_result(mysql));

구체적으로 코드를 살펴보세요:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>
#include <mysql/mysql.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <termios.h>
#include <mysql/mysql.h>
void process_result_set(MYSQL       *mysql, MYSQL_RES *result)
{
        int i =0;
        unsigned int fieldnum;
        //从结果集,获取表头信息
        MYSQL_FIELD *fields = mysql_fetch_fields(result);
        fieldnum = mysql_field_count(mysql);
        for (i=0; i<fieldnum; i++)
        {
            printf("%s\t", fields[i].name);
        }
        printf("\n");
        //从结果集, 按照行获取信息信息
        MYSQL_ROW row = NULL;
        //从结果集中一行一行的获取数据
        while (  row = mysql_fetch_row(result))
        {
            fieldnum = mysql_field_count(mysql); 
            //优化,我的行有多少列。。。。查找这样的api函数
            for (i=0; i<fieldnum; i++) //经过测试 发现 不是以0结尾的指针数组。。
            {
                printf("%s\t", row[i]);
            }
            printf("\n");
        }
}
int main()
{
    int         ret = 0, status = 0;
    MYSQL       *mysql;
    MYSQL_RES   *result;
    MYSQL_ROW   row;
    char        *query;
    mysql = mysql_init(NULL);
    mysql =mysql_real_connect(mysql, "localhost", "root", "123456", "mydb2", 0, NULL, CLIENT_MULTI_STATEMENTS);
    if (mysql == NULL)
    {
        ret = mysql_errno(mysql);
        printf("func mysql_real_connect() err\n");
        return ret;
    }
    else
    {
        printf(" ok......\n");
    }
    /* execute multiple statements */
status = mysql_query(mysql,
"DROP TABLE IF EXISTS test_table;\
CREATE TABLE test_table(id INT);\
INSERT INTO test_table VALUES(10);\
UPDATE test_table SET id=20 WHERE id=10;\
SELECT * FROM test_table;\
DROP TABLE test_table");
    if (status)
    {
        printf("Could not execute statement(s)");
        mysql_close(mysql);
        exit(0);
    }
    /* process each statement result */
    do {
            /* did current statement return data? */
            result = mysql_store_result(mysql);
            if (result)
            {
                /* yes; process rows and free the result set */
                process_result_set(mysql, result);
                mysql_free_result(result);
            }
            else /* no result set or error */
            {
                if (mysql_field_count(mysql) == 0)
                {
                    printf("%lld rows affected\n",
                    mysql_affected_rows(mysql));
                }
                else /* some error occurred */
                {
                    printf("Could not retrieve result set\n");
                    break;
                }
            }
        /* more results? -1 = no, >0 = error, 0 = yes (keep looping) */
        if ((status = mysql_next_result(mysql)) > 0)
                printf("Could not execute statement\n");
    } while (status == 0);
    mysql_close(mysql);
}

위는 하나의 함수 호출로 여러 문을 실행하는 MySQL 항목의 내용입니다. 내용이 궁금하시다면 PHP 중국어 넷(www.php.cn)을 주목해주세요!


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.