2011-04-04 8 views
0

質問は、私は彼が私がどんなフィードバックATMを得るカントオフラインカントーだと思う: 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は何も設定されていません。最後に挿入されたIDに設定しようとしていた方法がわかりません。

EDIT:

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

答えて

1

あなたは2番目のクエリを使用することなく、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私はこれをtryedしかしString.Format duhhで、問題は今返されたもので、私はラベルに設定し、私は返さ0を得る? –

+0

これは、それが格納されていないもので、mysqlはUserテーブルのUserIDであるAIプライマリキーを返しますと言っていますか? –

+0

ああ待っていない最後にselectステートメントを忘れてしまいました。最後に挿入したものを試してみました。もう一度同じエラーが出ます。ジャスティンが正しいかもしれないようです –