Using MySQL C API - check success of inserting rows using prepared statements

假如想象 提交于 2019-12-11 07:00:58

问题


I'm beginning to learn how to use the MySQL C API and have encountered prepared statements. I haven't used these before in other languages so it's all new to me.

I've looked online and I've figured out how to use prepared statements to retrieve data from a SELECT query, and now what I'm trying to do is to INSERT some data and find out if it was successful. I've got the first part pretty much down, but my question is: how can I find out if my INSERT was successfully executed?

I've had a read through some MySQL documents for the C API/prepared statements - and had a Google/search on SO. All I've been able to find examples of are SELECT prepared statements and nothing more.

I've attached some code that I've created, which successfully inserts a row.

#include <mysql/mysql.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "session.h"

char *createSessionId(MYSQL *dbc) {
    const char *sPS2 = "INSERT INTO `sessions` (`SessionID`) VALUES (?)";
    char *sID;
    MYSQL_STMT *stmt;
    MYSQL_BIND param[1];
    unsigned long l = 32;

    // Allocate a statement handle
    stmt = mysql_stmt_init(dbc);
    if(stmt == NULL) {
        printf("Unable to create new session: Could not init statement handle\n");
        return NULL;
    }

    // Init
    memset(param, 0, sizeof(param));
    sID = malloc(33);
    sprintf(sID, "01234567890123456789012345678901");
    if(mysql_stmt_prepare(stmt, sPS2, strlen(sPS2)) != 0) {
        printf("Unable to create new session: Could not prepare statement\n");
        return NULL;
    }

    // Initialise param structure
    param[0].buffer_type = MYSQL_TYPE_VARCHAR;
    param[0].buffer = sID;
    param[0].is_unsigned = 0;
    param[0].is_null = 0;
    param[0].length = &l;

    // Bind param structure to statement
    if(mysql_stmt_bind_param(stmt, param) != 0) {
        printf("Unable to create new session: Could not bind parameters\n");
        return NULL;
    }

    // Execute prepared statement
    if(mysql_stmt_execute(stmt) != 0) {
        printf("Unable to create new session: Could not execute statement\n");
        return NULL;
    }

    mysql_stmt_free_result(stmt);
    mysql_stmt_close(stmt);

    return sID;
}

回答1:


You already have the code in

if(mysql_stmt_execute(stmt) != 0) {
        printf("Unable to create new session: Could not execute statement\n");
        return NULL;
}

If that fails, you didn't insert any rows. The docs contain a full example

You can also use mysql_stmt_affected_rows() after a successful mysql_stmt_execute() to find out how many rows were insterted/updated/deleted.



来源:https://stackoverflow.com/questions/7935835/using-mysql-c-api-check-success-of-inserting-rows-using-prepared-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!