I can't use c api for MySQL prepared statement

Viewed 134

I am writing a hello-world level tryout of connecting MySQL with C. I followed each step in the MySQL Documentation and it still wont work. It is really frustrating.

I am trying to insert things into the table.

Insert statement:

insert into students_tbl values('?', ?, '?', '?');

Table structure:

| students_tbl | CREATE TABLE `students_tbl` (
  `name` varchar(40) DEFAULT NULL,
  `sal` int(11) DEFAULT NULL,
  `gender` varchar(10) DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |

C code:

    MYSQL_STMT *stmt = mysql_stmt_init(mysql);
    char *statement = "insert into students_tbl values('?', ?, '?', '?');";
    mysql_stmt_prepare(stmt, statement, strlen(statement));
    MYSQL_BIND bind[4];
    memset(bind, 0, sizeof(MYSQL_BIND) * 4);

    bind[0].buffer_type = MYSQL_TYPE_STRING;
    bind[0].buffer = (void *) "nana";
    bind[0].buffer_length = 4;
    bind[0].is_null = 0;
    bind[0].length = nullptr;

    int sal = 1234;
    bind[1].buffer_type = MYSQL_TYPE_LONG;
    bind[1].buffer = &sal;
    bind[1].buffer_length = sizeof(int);
    bind[1].is_null = 0;
    bind[1].length = nullptr;

    bind[2].buffer_type = MYSQL_TYPE_STRING;
    bind[2].buffer = (void *) "female";
    bind[2].buffer_length = 5;
    bind[2].is_null = 0;
    bind[2].length = nullptr;

    bind[3].buffer_type = MYSQL_TYPE_STRING;
    bind[3].buffer = (void *) "hahaha@hahaha.com";
    bind[3].buffer_length = 17;
    bind[3].is_null = 0;
    bind[3].length = nullptr;

    mysql_stmt_bind_param(stmt, bind);
    printf("%s", mysql_stmt_error(stmt));
    mysql_stmt_execute(stmt);
    printf("%s", mysql_stmt_error(stmt));

I tried to print something according to the Documentation, but got nothing at all.

I added this to check if mysql get the number of ? right:

int param_count = mysql_stmt_param_count(stmt);

The value of param_count is 0, surprisingly... I don't know why this may happen. I checked the character set of the table and switched it to utf8 and it still won't work...

Please help me get it right. Thx!!!

0 Answers
Related