2017-04-01 34 views
1

我必須在我的加載窗體窗體應用程序上自動生成新的AccountID。C#在Windows窗體應用程序中從數據庫生成新的ID

因此,例如,當用戶在「帳戶ID」的文本框中啓動窗體「添加新帳戶」時,我必須顯示數據庫的最新值。如果我在Windows窗體中的文本框中的數據庫中有兩個帳戶值將是三。

我的代碼完美的工作,如果我在數據庫中至少有一個帳戶,但是當我的數據庫爲空時,我得到異常。

這是我的代碼:

public int GetLatestAccountID() 
{ 
    try 
    { 
     command.CommandText = "select Max(AccountID)as maxID from Account"; 
     command.CommandType = CommandType.Text; 

     connection.Open(); 

     OleDbDataReader reader= command.ExecuteReader(); 

     if (reader.Read()) 
     { 
      int valueID = Convert.ToInt32(reader["maxID"]); 
      return valueID + 1; 
     } 

     return 1; 
    } 
    catch (Exception ex) 
    { 
     throw ex; 
    } 
    finally 
    { 
     if (connection!= null) 
     { 
      connection.Close(); 
     } 
    } 
} 

此外,我覺得答案在計算器:

object aa = DBNull.Value; 
int valueID = (aa as int?).GetValueOrDefault(); 

,但此行的代碼的工作,如果我的數據庫是空的,但是當我有一個帳戶,在數據庫,它會一直顯示在我的Windows窗體中的帳戶ID文本框中的值。我使用Microsoft Access 2007數據庫。

我很感激任何幫助。

回答

0

我猜你想:

public int GetLatestAccountID(string connectionString) 
{ 
    using(var dbConn = new OleDbConnection(connectionString)) 
    { 
     dbConn.Open(); 

     string query = "select Max(AccountID) from Account"; 
     using(var dbCommand = new OleDbCommand(query, dbConn)) 
     { 
      var value = dbCommand.ExecuteScalar(); 
      if ((value != null) && (value != DBNull.Value)) 
       return Convert.ToInt32(value) + 1; 

      return 1; 
     } 
    } 
} 

它看起來像你一旦打開你的數據庫連接,整個程序期間離開它打開。不要那樣做;導致競爭狀況和數據損壞。 .NET實現了數據庫連接池,因此您不需要打開連接就可以提高性能。

你也沒有告訴我們你在用什麼GetLatestAccountID。如果你試圖用它作爲主鍵,你也會遇到競爭狀況的問題。如果你想要一個主鍵,你應該讓數據庫創建它並在創建記錄後返回值。

+1

它已經有一段時間了,但是'ExecuteScalar'將有助於代替'ExecuteReader'。 – shahkalpesh

+0

噢,好主意@shahkalpesh!編輯。 –

+0

這工作!非常感謝你!! 是的,這是我的主鍵,但在數據庫中,我選擇的是數字,而不是自動編號。 –

0
public int GetLatestAccountID() 
{ 
    try 
    { 
     int accounts = 0; 

     command.CommandText = "select Max(AccountID)as maxID from Account"; 
     command.CommandType = CommandType.Text; 

     connection.Open(); 

     OleDbDataReader reader= command.ExecuteReader(); 

     if (reader.Read()) 
     { 
      accounts = Convert.ToInt32(reader["maxID"]) + 1; 
     } 

     return accounts; 
    } 
    catch (Exception ex) 
    { 
     throw ex; 
    } 
    finally 
    { 
     if (connection!= null) 
     { 
      connection.Close(); 
     } 
    } 
} 
+0

我嘗試,但它也不能正常工作。解決方案是使用Execute Scalar not Execute Reader。感謝您的回覆,並試圖幫助我。 –

+0

問題不在於'ExecuteReader',而是'Convert.ToInt32(reader [「maxID」])'不適用於可爲空的列。 –

0

您可以使用SELECT COUNT(column_name)FROM table_name;統計賬戶數量而不是選擇哪一個是最大的?

+0

是的,但如果我的數據庫是空的,它也不能工作。解決方法是使用: 執行標量不執行讀者 –

1

您可以進一步簡化它像下面,

選擇ISNULL(最大值(帳戶),0)作爲maxID從賬戶

相關問題