2011-04-04 138 views
0

問題與此相關的帖子,我覺得他是離線壽,所以我不能得到任何反饋大氣壓: MySql and inserting last ID problem remains 林不知道如果我是在完全盲目的,但在此代碼:轉換的CommandText串問題,回答問題

  // run the insert using a non query call 
      command.CommandText = cmd.ToString(); 
      command.ExecuteNonQuery(); 

      /* now we want to make a second call to MYSQL to get the new index 
       value it created for the primary key. This is called using scalar so it will 
       return the value of the SQL statement. We convert that to an int for later use.*/ 
      command.CommandText = "select last_insert_id();"; 
      id = Convert.ToInt32(command.ExecuteScalar()); 

      //------- the name id does not exist in the current context 

      // Commit the transaction. 
      transaction.Commit(); 
     } 
     catch (Exception ex) 
     { 
      Label10.Text = ": " + ex.Message; 

      try 
      { 
       // Attempt to roll back the transaction. 
       transaction.Rollback(); 
      } 
      catch 
      { 
       // Do nothing here; transaction is not active. 
      } 
     } 
    } 

id isnt設置爲任何內容,我不知道他是如何試圖將其設置爲最後插入的ID?

編輯:

int id = Convert.ToInt32(cmd.ExecuteScalar()); 
Label10.Text = Convert.ToString(id); 

回答

1

您應該能夠回到使用select @@IDENTITY;插入記錄的ID,而不必使用第二個查詢:

OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email) VALUES ('[email protected]'); select @@IDENTITY;" 
int id = Convert.ToInt32(cmd.ExecuteScalar()); 

審查您的老問題後,這應該是一樣的:

OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email) VALUES ('[email protected]'); SELECT LAST_INSERT_ID();" 
int id = Convert.ToInt32(cmd.ExecuteScalar()); 
+0

omg this w orked我嘗試了這一點,但與String.Format duhh,但現在的問題是什麼被返回,我把它設置爲一個標籤,我得到0返回? – 2011-04-04 20:37:32

+0

這不是它存儲的內容,mysql說它會返回我的用戶表中的UserID的AI主鍵? – 2011-04-04 20:38:54

+0

ahhh等不,我忘了最後的選擇語句tryed它與選擇最後插入,再次我得到相同的錯誤,所以看起來像賈斯汀可能是正確的 – 2011-04-04 20:41:49