开发者

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. I am using visual studio 2010,C# and oracle as my database

This is my code: **Hi guys. I tried as you told me but it did not work. It is crashing--+ $exception {"Unabl开发者_如何转开发e to cast object of type 'Oracle.DataAccess.Client.OracleDataReader' to type '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



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.

Edit : I found this solution on Oracle's documents. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜