2 brucel51 brucel51 于 2016.03.13 22:01 提问

使用 mysql c api 中,预处理查询条件 当过滤字段是字符串时
#include <stdio.h>
#include <mysql/mysql.h>
#include <string.h>

int main(void)
{
    // declares
    MYSQL * connection = NULL;
    MYSQL_STMT * stmt = NULL;
    MYSQL_BIND bind[3];
    MYSQL_BIND inbind;

    // preprocess
    bzero(bind, sizeof(bind));
    bzero(&inbind, sizeof(inbind));

    // declare MYSQL * ptr
    connection = mysql_init(NULL);
    if (NULL == connection)
    {
        fprintf(stderr, "mysql_init err!");
        return -1;
    }

    // connect
    connection = mysql_real_connect(connection, "localhost", "root", "root", "dblinuxcmysqlctr", 0, NULL, 0);
    if (NULL == connection)
    {
        fprintf(stderr, "mysql_real_connect err!");
        return -1;
    }

    /* 1. init */
    stmt = mysql_stmt_init(connection);

    /*   ********************************************************       */


    //char * insertsql = "select name from tlinuxcmysqlctr where age = ?;";

  // 这里不就可以过滤了,过滤出来没有数据,是为啥呀?
    char * insertsql = "select name from tlinuxcmysqlctr where name = ?;";


    /*   ********************************************************       */


    /* 2. prepare */
    if(mysql_stmt_prepare(stmt, insertsql, strlen(insertsql)))
    {
        printf("mysql_stmt_prepare err!\n");
        return -1;
    }
    char inpara1[50] = {0};
    //int inpara1 = 4;
    char outpara1[50] = {0};

    //bind[0].buffer_type = MYSQL_TYPE_LONG;
    //bind[0].buffer = &inpara1;
    //bind[0].buffer_length = sizeof(inpara1);
    bind[0].buffer_type = MYSQL_TYPE_STRING;
    strcpy(inpara1, "hello");
    bind[0].buffer = inpara1;
    bind[0].buffer_length = sizeof(inpara1);

    bind[1].buffer_type = MYSQL_TYPE_STRING;
    bind[1].buffer = outpara1;
    bind[1].buffer_length = 50;

    /* 3. bind_param */
    mysql_stmt_bind_param(stmt, bind + 0);

    /* 4. execute */
    if (mysql_stmt_execute(stmt))
    {
        printf("sorry\n");
    }
    else
    {
        /* 3.5 */
        mysql_stmt_bind_result(stmt, bind + 1);
        printf("bind[0].buffer = %s\n", (char *)bind[0].buffer);
        if (0 != mysql_stmt_store_result(stmt))
        {
            printf("store result stmt err\n");
            return -1;
        }
        else
        {

            printf("----------------------------table data--------------------------------\n");
            while (!mysql_stmt_fetch(stmt))
            {
                printf("name = %s\n", outpara1);
            }
        }
        mysql_stmt_free_result(stmt);
    }

    /* 5. close */
    mysql_stmt_close(stmt);

    // mysql_close
    mysql_close(connection);

    return 0;
}

1个回答

caozhy
caozhy   Ds   Rxr 2016.03.13 22:03
 char * insertsql = "select name from tlinuxcmysqlctr where `name` = ?;";

name是关键字

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!