将数据集转换为整数

本文关键字:整数 转换 数据集 | 更新日期: 2023-09-27 18:24:55

看,我有这个代码:

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,

将数据集转换为整数

您必须从数据集中选择第一个值,不能将完整的数据集转换为整数:

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

或者更简单(因为查询在数据集中返回一个整数):

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

然后您必须返回或保存结果,而不是只返回1。

我的朋友,您应该使用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
                }

看看如何检索数据,那么读取该整数(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作为结果