>  기사  >  데이터 베이스  >  MySQL 시작하기: 준비된 명령문의 사용

MySQL 시작하기: 준비된 명령문의 사용

黄舟
黄舟원래의
2017-01-19 15:35:091961검색

MySQL 클라이언트/서버 프로토콜은 준비된 명령문을 제공합니다. 이 함수는 mysql_stmt_init() 초기화 함수에 의해 반환된 MYSQL_STMT 명령문 핸들러 데이터 구조를 사용합니다. 여러 번 실행되는 명령문의 경우 전처리 실행이 효과적인 방법입니다. 먼저 명령문을 구문 분석하여 실행을 준비합니다. 그런 다음 초기화 함수에서 반환된 명령문 핸들을 사용하여 나중에 한 번 이상 실행합니다.

여러 번 실행되는 명령문의 경우 전처리 실행이 직접 실행보다 빠릅니다. 주된 이유는 쿼리에 대해 한 번의 구문 분석 작업만 수행되기 때문입니다. 직접 실행의 경우 명령문이 실행될 때마다 쿼리가 수행됩니다. 또한 준비된 문이 실행될 때마다 매개변수 데이터만 전송되므로 네트워크 트래픽이 줄어듭니다.
준비된 문의 또 다른 장점은 바이너리 프로토콜을 사용하여 클라이언트와 서버 간의 데이터 전송을 더욱 효율적으로 만든다는 것입니다.

Oracle의 자리 표시자 개념과 유사합니다! !
 
일반 단계:

mysql_stmt_init()를 사용하여 준비된 명령문 핸들을 생성합니다. 서버에서 준비된 명령문을 준비하려면 mysql_stmt_prepare()를 호출하여 SQL 문이 포함된 문자열을 전달합니다. 명령문이 결과 세트를 생성한 경우 mysql_stmt_result_metadata()를 호출하여 결과 세트 메타데이터를 얻습니다. 쿼리에서 반환된 열을 포함하는 결과 집합과 동일하지는 않지만 이 메타데이터 자체는 결과 집합의 형식을 취합니다. 메타데이터 결과 집합은 결과에 포함된 열 수를 나타내며 각 열에 대한 정보를 포함합니다. 매개변수의 값을 설정하려면 mysql_stmt_bind_param()을 사용하십시오. 모든 매개변수를 설정해야 합니다. 그렇지 않으면 문 실행 시 오류가 반환되거나 예측할 수 없는 결과가 생성됩니다. 명령문을 실행하려면 mysql_stmt_execute()를 호출하십시오. 명령문이 결과 세트를 생성한 경우 데이터 버퍼를 바인딩하고 mysql_stmt_bind_result()를 호출하여 행 값을 검색합니다. 더 이상 행이 발견되지 않을 때까지 mysql_stmt_fetch()를 반복적으로 호출하여 데이터를 한 행씩 버퍼로 가져옵니다. 매개변수 값을 변경하고 명령문을 다시 실행하여 3~6단계를 반복합니다.

자세한 내용은 코드보기

#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>
#include <termios.h>
#define STRING_SIZE 50
#define DROP_SAMPLE_TABLE "DROP TABLE IF EXISTS test_table"
#define CREATE_SAMPLE_TABLE "CREATE TABLE test_table(col1 INT,\
                                                 col2 VARCHAR(40),\
                                                 col3 SMALLINT,\
                                                 col4 TIMESTAMP)"
#define INSERT_SAMPLE "INSERT INTO test_table(col1,col2,col3) VALUES(?,?,?)" 
int main(int arg, char *args[])
{
    int             ret = 0, i=0;
    MYSQL           *mysql;
    MYSQL           *connect;
    MYSQL_RES       *result;
    MYSQL_ROW       row;
    MYSQL_FIELD     *fields;
    unsigned int    num_fields;
    //if (arg < 4)
    //{
    //  printf("please enter: %s localhost user password dbname\n", args[0]);
    //  return -1;
    //}
    mysql = mysql_init(NULL);
    //连接到mysql server
    //connect = mysql_real_connect(mysql, args[1], args[2], args[3], args[4],0, 0, 0);
    //connect = mysql_real_connect(mysql, "localhost", "root", a, args[4],0, 0, 0);
    connect = mysql_real_connect(mysql, "localhost", "root", "123456", "mydb2", 0, NULL, 0 );
    if (connect == NULL)
    {
        printf("connect error, %s\n", mysql_error(mysql));
        return -1;
    }
    ret = mysql_query(connect, "SET NAMES utf8");       //设置字符集为UTF8
    if (ret != 0)
    {
        printf("设置字符集错误, %s\n", mysql_error(mysql));
        return ret;
    }
    MYSQL_STMT    *stmt;
    MYSQL_BIND    bind[3];
    my_ulonglong  affected_rows;
    int           param_count;
    short         small_data;
    int           int_data;
    char          str_data[STRING_SIZE];
    unsigned long str_length;
    my_bool       is_null;
    if (mysql_query(mysql, DROP_SAMPLE_TABLE))
    {
      fprintf(stderr, " DROP TABLE failed\n");
      fprintf(stderr, " %s\n", mysql_error(mysql));
      exit(0);
    }
    if (mysql_query(mysql, CREATE_SAMPLE_TABLE))
    {
      fprintf(stderr, " CREATE TABLE failed\n");
      fprintf(stderr, " %s\n", mysql_error(mysql));
      exit(0);
    }
    /* Prepare an INSERT query with 3 parameters */
    /* (the TIMESTAMP column is not named; the server */
    /*  sets it to the current date and time) */
    stmt = mysql_stmt_init(mysql); //初始化 预处理环境 生成一个预处理句柄
    if (!stmt)
    {
      fprintf(stderr, " mysql_stmt_init(), out of memory\n");
      exit(0);
    }
    if (mysql_stmt_prepare(stmt, INSERT_SAMPLE, strlen(INSERT_SAMPLE))) //预处理环境中 准备sql
    {
      fprintf(stderr, " mysql_stmt_prepare(), INSERT failed\n");
      fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
      exit(0);
    }
    fprintf(stdout, " prepare, INSERT successful\n");
    /* Get the parameter count from the statement */
    param_count= mysql_stmt_param_count(stmt);   //预处理环境中 求绑定变量的个数
    fprintf(stdout, " total parameters in INSERT: %d\n", param_count);
    if (param_count != 3) /* validate parameter count */
    {
      fprintf(stderr, " invalid parameter count returned by MySQL\n");
      exit(0);
    }
    /* Bind the data for all 3 parameters */
    memset(bind, 0, sizeof(bind));
    /* INTEGER PARAM */   
    /* This is a number type, so there is no need to specify buffer_length */
    bind[0].buffer_type= MYSQL_TYPE_LONG;  //为第一个绑定变量设置类型和 输入变量的内存首地址
    bind[0].buffer= (char *)&int_data;
    bind[0].is_null= 0;
    bind[0].length= 0;
    /* STRING PARAM */
    bind[1].buffer_type= MYSQL_TYPE_STRING; //为第2个绑定变量设置类型和 输入变量的内存首地址
    bind[1].buffer= (char *)str_data;
    bind[1].buffer_length= STRING_SIZE;
    bind[1].is_null= 0;
    bind[1].length= &str_length;
    /* SMALLINT PARAM */
    bind[2].buffer_type= MYSQL_TYPE_SHORT; //为第3个绑定变量设置类型和 输入变量的内存首地址
    bind[2].buffer= (char *)&small_data;
    bind[2].is_null= &is_null;
    bind[2].length= 0;
    /* Bind the buffers */
    if (mysql_stmt_bind_param(stmt, bind)) //把绑定变量设置到 预处理环境中
    {
      fprintf(stderr, " mysql_stmt_bind_param() failed\n");
      fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
      exit(0);
    }
    /* Specify the data values for the first row */ //插入第一条记录
    int_data= 10;             /* integer */
    strncpy(str_data, "MySQL", STRING_SIZE); /* string  */
    str_length= strlen(str_data);
    /* INSERT SMALLINT data as NULL */
    is_null= 1;
    /* Execute the INSERT statement - 1*/
    if (mysql_stmt_execute(stmt))
    {
      fprintf(stderr, " mysql_stmt_execute(), 1 failed\n");
      fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
      exit(0);
    }
    /* Get the total number of affected rows */
    affected_rows= mysql_stmt_affected_rows(stmt);
    fprintf(stdout, " total affected rows(insert 1): %lu\n",
                    (unsigned long) affected_rows);
    if (affected_rows != 1) /* validate affected rows */
    {
      fprintf(stderr, " invalid affected rows by MySQL\n");
      exit(0);
    }
    /* Specify data values for second row, then re-execute the statement */
    int_data= 1000;   //插入第一条记录
    strncpy(str_data, "The most popular Open Source database", STRING_SIZE);
    str_length= strlen(str_data);
    small_data= 1000;         /* smallint */
    is_null= 0;               /* reset */
    /* Execute the INSERT statement - 2*/
    if (mysql_stmt_execute(stmt))
    {
      fprintf(stderr, " mysql_stmt_execute, 2 failed\n");
      fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
      exit(0);
    }
    /* Get the total rows affected */
    affected_rows= mysql_stmt_affected_rows(stmt);
    fprintf(stdout, " total affected rows(insert 2): %lu\n",
                    (unsigned long) affected_rows);
    if (affected_rows != 1) /* validate affected rows */
    {
      fprintf(stderr, " invalid affected rows by MySQL\n");
      exit(0);
    }
    /* Close the statement */
    if (mysql_stmt_close(stmt))
    {
      fprintf(stderr, " failed while closing the statement\n");
      fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
      exit(0);
    }
     mysql_close(connect);      //断开与SQL server的连接
}

위는 MySQL을 시작하기 위해 준비된 문장을 사용하는 내용이며, 더 많은 관련 내용은 PHP 중국어 홈페이지(www. php.cn)!


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