在手冊頁上; http://dev.mysql.com/doc/refman/5.0/en/mysql-insert-id.html 據說「返回前一個INSERT或UPDATE語句爲AUTO_INCREMENT列生成的值」。mysql_insert_id()問題與MySQL 5.0.67 + Windows + VC++ 2008
問題是,更新後它並不適合我。
真正的需求是,我試圖更新表中的一行(用「WHERE」條件更新),然後,如果某一行確實已更新,請獲取它的完整詳細信息。 所以首先我更新,然後我需要它的id來獲取它的詳細信息與SELECT語句。
下面是一個例子代碼顯示問題:
#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();
}
如何使這個mysql_insert_id()函數工作,在這種情況下,或者如何更新和一個statament選擇?
請注意,我在這個例子中插入一行所以它會做出一些列的你,所以你可以看到..
謝謝!編輯: 看看我對這個問題的最新回覆。我給出了更爲清晰的描述。
是的,這是一個問題。 我希望有另一種方式來實現它,否則執行一個查詢,其中包括更新和上一次更新的選擇...查看我的意思? – Poni 2010-03-04 13:38:19
我很想知道誰在討厭我的問題:) – Poni 2010-03-04 14:08:53