2013-07-24 43 views
2

看看我有這樣的代碼:轉換數據集到整數

private void obtengoUltimoComienzoColocado() 
    { 
     ManejoUsuarios lAdm = new ManejoUsuarios(); 
     lblTodoOK.Text = lAdm.LevantoUltimoIDBarco().ToString(); 

    } 

public int LevantoUltimoIDBarco() 
     { 
      ConexionBD lP = new ConexionBD(); 
      try 
      { 
       string lQuery = "Select Max(idBarco) as UltimoID From Comienzos;"; 
       Convert.ToInt32(lP.ObtenerRegistro(lQuery)); 
       return 1; 
      } 
      catch (Exception ex) 
      { 
       return 0; 
      } 

     } 

public DataSet ObtenerRegistro(string SqlQuery) 
    { 
     DataSet lResult; 
     SqlConnection lSqlConnection = new SqlConnection("Data Source=SEBA-PC\\sqlexpress;Initial Catalog=Batalla_Naval;Integrated Security=True"); 
     SqlCommand lSqlCommand = null; 
     try 
     { 
      lSqlCommand = new SqlCommand(); 
      lSqlCommand.CommandText = SqlQuery; 
      lSqlCommand.CommandType = CommandType.Text; 

      SqlDataAdapter lAdapter = new SqlDataAdapter(lSqlCommand); 
      lResult = new DataSet(); 
      lSqlConnection.Open(); 
      lSqlCommand.Connection = lSqlConnection; 
      lAdapter.Fill(lResult); 
     } 
     catch (Exception) 
     { 
      throw; 
     } 
     finally 
     { 
      lSqlConnection.Close(); 
     } 
     return lResult; 
    } 

正如你可以看到我用三個函數來訪問數據庫,並從表Comienzos最大ID,但是當我要轉換的數據集,你如何檢索數據,那麼正確的代碼讀取整數INT32 LevantoUltimoIDBarco返回我0功能,

回答

2

您必須選擇從數據集的第一個值,你不能將一個完整的數據集到整數:

Convert.ToInt32(lP.ObtenerRegistro(lQuery).Tables[0].Rows[0][0]); 

或簡單(因爲查詢數據集中返回一個整數):

(Int32)(lP.ObtenerRegistro(lQuery).Tables[0].Rows[0][0]); 

然後你不得不返回或保存的結果,而不是隻返回1.

+0

謝謝!我在哪裏插入代碼? – Spresno

+0

如果你有這樣的代碼:'Convert.ToInt32(lP.ObtenerRegistro(lQuery));' – Raidri

+0

真的有用,我做到了!謝謝! – Spresno

0

綜觀(MAX())是以下

string lQuery = "Select Max(idBarco) as UltimoID From Comienzos;"; 
DataSet ds = lP.ObtenerRegistro(lQuery); 
return Convert.ToInt32(ds.Tables[0].Rows[0][0] == DBNull.Value ? 0 : ds.Tables[0].Rows[0][0]); 

但是,如果你的表中沒有記錄的MAX(idBarco)將返回的DBNull作爲結果

1

我的朋友,你守ld使用ExecuteScalar返回單個值,而不是適配器並填充數據集。

SqlConnection lSqlConnection = new SqlConnection("Data Source=SEBA-PC\\sqlexpress;Initial Catalog=Batalla_Naval;Integrated Security=True"); 
       SqlCommand lSqlCommand = null; 
       try 
       { 
        lSqlCommand = new SqlCommand(); 
        lSqlCommand.CommandText = SqlQuery; 
        lSqlCommand.CommandType = CommandType.Text; 
        var result = lSqlCommand.ExecuteScalar(); 
        int MyID = Convert.ToInt32(result); 

       } 
       catch(ex) 
       { 
        // DO SOMETHING 
       }