Jacob
Jacob

Reputation: 381

mysql query Insert does not work

I am trying to insert a field into a mysql db but it does not work.

I have tried to change around abit using just "insert into image", using an query string insteed of the string literal. I looked here to try understand if syntax was different or something.

I think Iam doing it according to the API.

Here my setup

From the out put i get

i = 1
MySQL Tables in mysql database:
images

here is the code.

Any ideas?

    /* Simple C program that connects to MySQL Database server*/
#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>
   int main() {
      MYSQL *conn;
      MYSQL_RES *res;
      MYSQL_ROW row;
      char *server = "localhost";
      char *user = "root";
      //set the password for mysql server here
      char *password = "********"; 
      char *database = "myDB";
      conn = mysql_init(NULL);
      if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0))
      {
          fprintf(stderr, "%s\n", mysql_error(conn));
          exit(1);
      }
      /* send SQL query */
      if (mysql_query(conn, "show tables") == 1)
      {
          fprintf(stderr, "%s\n", mysql_error(conn));
          exit(1);
      }
    int i = mysql_query(conn ,"INSERT INTO `myDB`.`images` (`id`, `date`, `path`) VALUES (NULL, CURRENT_TIMESTAMP, 'mypath/foo/bar')");
    printf("i = %d \n", i);
      res = mysql_use_result(conn);
      /* output table name */
      printf("MySQL Tables in mysql database:\n");
      while ((row = mysql_fetch_row(res)) != NULL)
      {
          printf("%s \n", row[0]);
      }
      /* close connection */
      mysql_free_result(res);
      mysql_close(conn);
    return 0;
    }

Upvotes: 0

Views: 219

Answers (3)

Jacob
Jacob

Reputation: 381

I manages to get it working now. I found some examples here that i tried to recreate and got it working.

It is not entirely same as other query

      if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0))
  {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
  }
  if (mysql_query(conn ,"INSERT INTO images VALUES (NULL , CURRENT_TIMESTAMP , 'awesome')"))
  {
     fprintf(stderr, "Error: could not execute query \n");
      exit(1);
  }
    int my_bool = mysql_commit(conn);

  mysql_free_result(res);
  mysql_close(conn);
return 0;

Upvotes: 0

Nagesh
Nagesh

Reputation: 437

confirm that your ID column is not a primary key, because primary key does not allow null columns

Upvotes: 0

mrUlrik
mrUlrik

Reputation: 170

Assuming id is the primary id and INT, it may be auto-increment. If that's the case, take out id from your statement.

INSERT INTO `myDB`.`images` (`date`, `path`) VALUES (CURRENT_TIMESTAMP, 'mypath/foo/bar');

It would be helpful to answer the question if we knew the format of the table. This is assuming date is TIMESTAMP and path is CHAR or most likely VARCHAR.

Upvotes: 1

Related Questions