2011-04-04 52 views
1

確定後,大量的閱讀,並試圖我仍然不能似乎得到這個工作:MySQL和插入最後一個ID問題仍然

 OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email) VALUES ('[email protected]'); SELECT LAST_INSERT_ID();", cn); 

cmd.ExecuteNonQuery(); 
       using (OdbcDataReader reader = cmd.ExecuteReader()) 
       { 

       string theUserId = String.Format("{0}", reader.GetString(0)); 
       Label10.Text = theUserId; 

表:

User 
-------- 
UserID (auto increment, pk) 
Email 

運行在調試模式下我上得到錯誤這條線,

  using (OdbcDataReader reader = cmd.ExecuteReader()) 

,並

cmd.ExecuteNonQuery(); 

Mysql在這一行上說它的語法錯誤SELECT LAST_INSERT_ID();",cn);但從什麼是閱讀這是合法的。

確切的錯誤:

ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.5.9]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT LAST_INSERT_ID()' at line 1 

編輯:Justins方法:

using (OdbcConnection connection = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;")) 
{ 
    // ODBC command and transaction objects 
    OdbcCommand command = new OdbcCommand(); 
    OdbcTransaction transaction = null; 

    // tell the command to use our connection 
    command.Connection = connection; 

    try 
    { 
     // open the connection 
     connection.Open(); 

     // start the transaction 
     transaction = connection.BeginTransaction(); 

     // Assign transaction object for a pending local transaction. 
     command.Connection = connection; 
     command.Transaction = transaction; 

     // TODO: Build a SQL INSERT statement 
     OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email, FirstName, SecondName, DOB, Location, Aboutme, username, password) VALUES ('" + TextBox1.Text + "', '" + TextBox2.Text + "', '" + TextBox3.Text + "', '" + TextBox4.Text + "', '" + TextBox5.Text + "', '" + TextBox6.Text + "', '" + TextBox7.Text + "', '" + TextBox8.Text + "')", connection); 

     // 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 doesnt 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. 
     } 
    } 
} 
+1

您是否允許在1'OdbcCommand'中執行2個查詢/語句?如果你在兩個單獨的項目中完成,會發生什麼? – Wrikken 2011-04-04 19:05:06

+0

@Wrikken,就是這個問題.net mySQL ODBC驅動程序不允許在該上下文中使用多個命令。你必須撥打兩個不同的電話。我之前遇到過這個問題;) – Justin 2011-04-04 19:24:49

+0

嘗試使用字符串,而不是使用字符串和連接參數創建另一個OdbcCommand對象。然後將command.CommandText設置爲該String。我想在創建第二個OdbcCommand對象時會發生一些奇怪的事情。 – Justin 2011-04-05 15:32:25

回答

4

澄清,MySQL的.NET ODBC驅動程序不允許多個命令,就像你所描述的運行。您必須進行兩個獨立的呼叫並將其包裝在交易中。

// open a new connection using a default connection string I have defined elsewhere 
using(OdbcConnection connection = new OdbcConnection(s_connectionString)) 
{ 
     // ODBC command and transaction objects 
     OdbcCommand command = new OdbcCommand(); 
     OdbcTransaction transaction = null; 

     // tell the command to use our connection 
     command.Connection = connection; 

     try 
     { 
      // open the connection 
      connection.Open(); 

      // start the transaction 
      transaction = connection.BeginTransaction(); 

      // Assign transaction object for a pending local transaction. 
      command.Connection = connection; 
      command.Transaction = transaction; 

      // TODO: Build a SQL INSERT statement 
      StringBuilder SQL = new StringBuilder(); 

      // run the insert using a non query call 
      command.CommandText = SQL.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()); 

      // Commit the transaction. 
      transaction.Commit(); 
    } 
    catch(Exception ex) 
    { 
      Debug.WriteLine(ex.Message); 

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

我收到一個錯誤:錯誤[42000] [MySQL] [ODBC 3.51驅動程序] [mysqld-5.5.9]你的SQL語法錯誤;查看與您的MySQL服務器版本相對應的手冊,以找到在「System.Data.Odbc」附近使用的正確語法。OdbcCommand'在行1 – 2011-04-04 20:58:53

0

如果你的電子郵件是唯一可以使用

Select ID From User where Email='[email protected]' 

你確信你總是得到正確的答案。

如果你的電子郵件是不是唯一的,你應該使用鎖,以確保只有線程執行查詢,然後將您的插入後,使用此查詢

Select Max(ID) From User 
+0

ahh對不起,電子郵件只是一個例子我不知道電子郵件直到它插入到數據庫因此,爲什麼我需要上次交易 – 2011-04-04 19:28:02

0

一種解決方法:

  1. 添加out param to your query:
  2. 查詢內部使用SET @OpParam = SELECT LAST_INSERT_ID();
  3. 在你的代碼中,如果((int)@ OpParam.Value> 0){pull out}。
  4. 此外,如果運行選擇,則改爲NonQuery,使用ExecuteScalar()。

希望它可以幫助你。

+0

executablecalar用於選擇。嘗試設置出參數仍然沒有喜悅 – 2011-04-05 19:18:54

+0

如果您需要檢索第一個單元格的值,您還可以使用插入,更新刪除或多個語句 – 2011-04-06 09:40:20

+0

如果您要返回標識並在代碼上需要它,則需要ExecuteScalar ,而不是NonQuery,因爲Non Query將爲您提供受查詢影響的行數。 – 2011-04-06 09:41:31