简体   繁体   English

如何使用c#从数据库返回一个整数?

[英]How do you return an integer from a database using c#?

Hi everyone. 嗨,大家好。 I am selecting a column from a table which returns a field with a number. 我从表中选择一个列,该列返回带有数字的字段。 I wish to return this number to an integer in c# so that I can increment the integer by 1 after getting it. 我希望将此数字返回到c#中的整数,以便在获取它之后我可以将整数增加1。 I am using visual studio 2010,C# and oracle as my database 我使用visual studio 2010,C#和oracle作为我的数据库

This is my code: **Hi guys. 这是我的代码: **大家好。 I tried as you told me but it did not work. 我按照你告诉我的方式尝试但是没有用。 It is crashing--+ $exception {"Unable to cast object of type 'Oracle.DataAccess.Client.OracleDataReader' to type 'System.IConvertible'."} System.Exception {System.InvalidCastException} 崩溃 - + $ exception {“无法将'Oracle.DataAccess.Client.OracleDataReader'类型的对象强制转换为'System.IConvertible'。”} System.Exception {System.InvalidCastException}

** **

public static int GetRunNumber(string date)
    {
        int result;

        DatabaseAdapter dba = DatabaseAdapter.GetInstance();
        string sqlQuery = "SELECT RUN FROM LOAD_CONTROL " +
                          "WHERE START_DATE = (SELECT MAX(START_DATE) " +
                          "FROM LOAD_CONTROL " +
                          "WHERE LOAD_DATE = to_date('" + date + "', 'dd/mm/yyyy')) " +
                          "AND LOAD_DATE = to_date('" + date + "', 'dd/mm/yyyy') ";

        result = Convert.ToInt32(dba.QueryDatabase(sqlQuery));
        return result;
    } 

your comment suggests that the result will be a OracleDataReader - in this case use 您的评论表明结果将是OracleDataReader - 在这种情况下使用



var reader = dba.QueryDatabase(sqlQuery);
if(reader.Read())
{
  return reader.GetInt32(0);
}
// else error
throw new Exception("no result found");

You can use Parse or TryParse methods of Int32 Structure. 您可以使用Int32 Structure的ParseTryParse方法。

Edit : I found this solution on Oracle's documents. 编辑:我在Oracle的文档中找到了这个解决方案。 It is a different approach but might work for you. 这是一种不同的方法,但可能适合您。

// Connection string for your app
string constr = "User Id=scott;Password=tiger;Data Source=oracle"; 

// Creates new connection object.
OracleConnection con = new OracleConnection(constr);
con.Open();

// Change below with your query.
string cmdstr = "SELECT * FROM EMPINFO";
OracleConnection connection = new OracleConnection(constr);
OracleCommand cmd = new OracleCommand(cmdstr, con);
OracleDataReader reader = cmd.ExecuteReader();

// Returns the first column of the first row returned from your query and 
// converts it to Int32. You should replace '0' with the column no you desire.
return reader.GetInt32(0);

For more info you can check the document I mentioned. 有关详细信息,您可以查看我提到的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM