Hello!
On the manual page; http://dev.mysql.com/doc/refman/5.0/en/mysql-insert-id.html It is said that "Returns the value generated for an AUTO_INCREMENT column by the previous INSERT or UPDATE statement."
The problem is that it doesn't really work for me after an update.
The real need is that I'm trying to update a row in a table (updated with a "WHERE" conditions) and then, if a row indeed was updated, get it's full details. So first I UPDATE, then I need it's id to get it's details with a SELECT statement.
Here's an example code which shows the problem:
#define _WIN32_WINNT 0x0400
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <winsock.h>
#include "C:/Program Files (x86)/MySQL/MySQL Server 5.0/include/mysql.h"
#pragma comment(lib, "C:/Program Files (x86)/MySQL/MySQL Server 5.0/lib/opt/libmysql.lib")
void main()
{
MYSQL *conn = mysql_init(NULL);
if(conn == NULL)
throw "error";
if(mysql_real_connect(
conn,
"127.0.0.1",
"user", "passwd",
NULL,
0,
NULL,
0) != conn)
throw "error";
int nRet = 0;
char szInsert[] = "INSERT INTO db_transation_test.tbl_transactions SET amount=71, ses=72";
nRet = mysql_real_query(conn, szInsert, sizeof(szInsert));
if(nRet != 0)
{
printf("%s\n", mysql_error(conn));
throw;
}
my_ulonglong inserted_id = mysql_insert_id(conn);
///////// the real issue of my post starts here /////////
char szUpdateTemplate[] = "UPDATE db_transation_test.tbl_transactions SET amount=123 WHERE id_transaction=%lld";
char szUpdate[1024];
nRet = sprintf_s(szUpdate, sizeof(szUpdate), szUpdateTemplate, inserted_id);
nRet = mysql_real_query(conn, szUpdate, nRet);
if(nRet != 0)
{
printf("%s\n", mysql_error(conn));
throw;
}
my_ulonglong updated_id = mysql_insert_id(conn); // returns ZERO instead of 'inserted_id' :(
_getch();
}
How do I make this mysql_insert_id() function work in that case, or alternatively how do I UPDATE and SELECT in one statament?
Note that I've INSERTed a row in this example so it'll make some row for you, so you can see..
Thank you!
EDIT: Check out my latest reply to this question. I gave a much more clear description.