OledbDataReader function to return integer - c#

Working in C#, I'm having trouble with a function. Function runs a query and the query is supposed to return one integer value but I'm having trouble returning it. I keep getting errors like:
Unable to cast object of type oleDbDataReader to type Int32
Specified cast is not valid
Not sure how to do this with C# and OleDbDataReader. My code is below
public static int FifthQuery()
{
int _value = 0;
OleDbConnection _connectMe = Utilities.OledbConnect();
OleDbCommand _query1 = new OleDbCommand();
_query1.Connection = _connectMe;
_query1.CommandText = "SELECT count(*) FROM GIS.PERSONS where Name_Prefix = 'Dr.'";
OleDbDataReader _reader = _query1.ExecuteReader();
_reader.Read();
//_value = Convert.ToInt32(_reader);
_value = _reader.GetInt32(0);
return _value;
}

Since you using COUNT(*), using ExecuteScalar would be better approach.
Executes the query, and returns the first column of the first row in
the result set returned by the query.
int _value = (int)_query1.ExecuteScalar();
Also use using statement to dispose your OleDbConnection and OleDbCommand.
using(OleDbConnection _connectMe = Utilities.OledbConnect())
using(OleDbCommand _query1 = _connectMe.CreateCommand())
{
_query1.CommandText = "SELECT count(*) FROM GIS.PERSONS where Name_Prefix = 'Dr.'";
_connectMe.Open();
int _value = (int)_query1.ExecuteScalar();
}

Related

Proper use of AddWithValue in C# to Db method

Trying to do the following:
public static int GetJobStatusByNumber(int jobNumber)
{
SqlConnection connection = null;
try
{
connection = new SqlConnection(connString);
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = #"select STATUS from JOB
where JOB_NUMBER = #jobNumber";
cmd.Parameters.AddWithValue("#jobNumber", jobNumber);
int result = ((int)cmd.ExecuteScalar());
return result;
}
finally
{
if (connection != null)
connection.Close();
}
}
Thouht I can add the varible 'jobNumber' to the query by using 'AddWithValue' but I'm getting a cast error
Message: System.InvalidCastException : Specified cast is not valid.
What's wrong here?
Thanks.
ExecuteScalar() returns the first column of the first row in the result set returned by the query.
2 scenarios are possible:
the first column is not a int.
the query return 0 rows - in that case ExecuteScalar() will return null.
for point 1 - make sure that the first column is an int.
for point 2 - make sure you have rows. possible solution will be:
var result = 0;
var tempResult = cmd.ExecuteScalar();
if (tempResult != null) {
result = (int)tempResult;
}

Retrieve results of a stored procedure on c#

I have a stored procedure that selects and returns a list of years. In sql server I call it like this:
DECLARE #return_value int
EXEC #return_value = [dbo].[TestName]
#del= 0
SELECT 'Return Value' = #return_value
In order to receive the list.
My SP looks like this:
USE [TestTable]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[TestName] (#delvarchar(7))
AS
BEGIN
SELECT YEAR( [added]) AS year FROM [MyTable]
GROUP BY YEAR( [added])
ORDER BY YEAR( [added]) DESC
END
I want to do the same from c# though and pass the values in a List.
What I am trying is:
using (var conn = new SqlConnection(constr))
using (var command = new SqlCommand("TestName", conn)
{
CommandType = CommandType.StoredProcedure
})
{
command.Parameters.AddWithValue("#del", del);
SqlParameter retval = command.Parameters.Add("#return_value", SqlDbType.VarChar);
retval.Direction = ParameterDirection.ReturnValue;
conn.Open();
command.ExecuteNonQuery();
int retunvalue = (int)command.Parameters["#return_value"].Value;
conn.Close();
return retunvalue;
}
This does not return any values though, instead it only returns 0. What am I doing wrong and how can I get the list inside a variable as specified?
Editing the code following John Hanna's advise I have something like this:
public List<string> getYears(string constr, int del)
{
using (var conn = new SqlConnection(constr))
using (var command = new SqlCommand("TestName", conn)
{
CommandType = CommandType.StoredProcedure
})
{
command.Parameters.AddWithValue("#del", del);
List<string> retunvalue = new List<string>();
conn.Open();
SqlDataReader reader;
reader = command.ExecuteReader();
conn.Close();
return retunvalue;
}
}
And by adding a breakpoint in order to explore reader I see that it is only contains errors:
Depth = '(reader).Depth' threw an exception of type 'System.InvalidOperationException'
As for Krishna's answer, dtList was empty with a count of 0, and I am not sure how to implement Badhon's suggestion.
ExecuteNonQuery() is so called because its for use with something that doesn't query the data. The 0 you get back is the number of rows the command changed.
Instead use ExecuteReader() and you will get back a SqlDataReader object that you can call Read() on to move through rows and then examine the details of each.
If you want to return that to another method use ExecuteReader(CommandBehavior.CloseConnection) and then rather than Close() or Dispose() the connection after you are finished, Close() or Dispose() the reader and that will close the connection then.
If you only have one row with one column (or for some reason only care about the first column of the first row even though there is more), then ExecuteScalar() is a convenient way to get just that single value.
You shouldn't use ExecuteNonQuery, rather use ExecuteDataSet as follow:
public List<DSM_DocPropIdentify> GetDocPropIdentify(string docPropIdentifyID, string action, out string errorNumber)
{
errorNumber = string.Empty;
List<DSM_DocPropIdentify> docPropIdentifyList = new List<DSM_DocPropIdentify>();
DatabaseProviderFactory factory = new DatabaseProviderFactory();
SqlDatabase db = factory.CreateDefault() as SqlDatabase;
using (DbCommand dbCommandWrapper = db.GetStoredProcCommand("GetDocPropIdentify"))
{
// Set parameters
db.AddInParameter(dbCommandWrapper, "#DocPropIdentifyID", SqlDbType.VarChar, docPropIdentifyID);
db.AddOutParameter(dbCommandWrapper, spStatusParam, DbType.String, 10);
// Execute SP.
DataSet ds = db.ExecuteDataSet(dbCommandWrapper);
if (!db.GetParameterValue(dbCommandWrapper, spStatusParam).IsNullOrZero())
{
// Get the error number, if error occurred.
errorNumber = db.GetParameterValue(dbCommandWrapper, spStatusParam).PrefixErrorCode();
}
else
{
if (ds.Tables[0].Rows.Count > 0)
{
DataTable dt1 = ds.Tables[0];
docPropIdentifyList = dt1.AsEnumerable().Select(reader => new DSM_DocPropIdentify
{
DocPropIdentifyID = reader.GetString("DocPropIdentifyID"),
DocPropertyID = reader.GetString("DocPropertyID"),
DocCategoryID = reader.GetString("DocCategoryID"),
DocTypeID = reader.GetString("DocTypeID"),
OwnerID = reader.GetString("OwnerID"),
IdentificationCode = reader.GetString("IdentificationCode"),
IdentificationSL = reader.GetString("IdentificationSL"),
AttributeGroup = reader.GetString("AttributeGroup"),
IdentificationAttribute = reader.GetString("IdentificationAttribute"),
IsRequired = reader.GetInt16("IsRequired"),
IsAuto = reader.GetInt16("IsAuto"),
SetOn = reader.GetString("SetOn"),
SetBy = reader.GetString("SetBy"),
ModifiedOn = reader.GetString("ModifiedOn"),
ModifiedBy = reader.GetString("ModifiedBy"),
Status = reader.GetInt32("Status"),
Remarks = reader.GetString("Remarks")
}).ToList();
}
}
}
return docPropIdentifyList;
}
Is dbo.TestName returns you a table or a value. If that returns you a table, then you would have to execute DataAdapter or execute DataReader. You should replace the above statement
as
DataTable dtList=new DataTable();
SqlDataAdapter adapter=new SqlDataAdapter();
adapter.SelectCommand=command;
adapter.Fill(dtList);
Then you can iterate through the datatable and add that to your list
List<Object> listObj=new List<Object>();
foreach(var rows in dtList.Rows)
{
listObj.Add(rows["Column_name"]);
}
I analysed your query, and found that, the statement
DECLARE #return_value int
EXEC #return_value = [dbo].[TestName]
#del= 0
SELECT 'Return Value' = #return_value
returns multiple tables. You can remove the last statement which is redundant.
SELECT 'Return Value' = #return_value
The datatable will now be populated with values.
Let me know if that works.

"Select count()" returns wrong value

I am trying to determine if a specific value exists in a Oracle database table.
I used a query with "select count(*)", "select count(1)" and select count(<col_name>)" but keep getting the wrong result. When I use SQL Developer and run the query I get zero for the count. However, in the DAL, I get 1. I am guessing it is returning the number of row rather than the count itself. I tried both executeScalar() and ExecuteReader().
public override bool zipExists(string sZipCode)
{
OracleConnection conn = new OracleConnection(this.OraDataConnectionString);
OracleCommand oraCmd = new OracleCommand();
decimal iNumEntries = 0;
string sQuery = "select count(ZIPCODEID) as ZipCount from ZIPCODE where ZIPCODE = :ZipCode";
SetOraCommandType(oraCmd, CommandType.Text, sQuery);
conn.Open();
oraCmd.Connection = conn;
oraCmd.BindByName = true;
AddParamToOraCmd(oraCmd, "ZipCode", OracleDbType.Varchar2, 11, ParameterDirection.Input, sZipCode);
using (OracleConnection cn = new OracleConnection(this.OraDataConnectionString))
{
oraCmd.Connection = cn;
cn.Open();
iNumEntries = (decimal)oraCmd.ExecuteScalar();
}
return iNumEntries > 0;
also tried:
OracleDataReader sqlReader = oraCmd.ExecuteReader();
try
{
if (sqlReader.Read())
{
if (sqlReader["ZipCount"] != DBNull.Value)
iNumEntries = Convert.ToInt16(sqlReader["ZipCount"]);
}
}
}
return iNumEntries > 0;
I try you code on my table but pointing to some column and giving a select count(EN_Qty) as ZipCount from PSLAT.FSDEV.dbo.PS_EN_GEN_INTFC_BI where EN_Qty = '2600' works on my end so where in the code exactly are you experiencing an issue..? fyi I replaced my table with your query and assigned a value to the where clause.. so you query looks right.. however I would do an order by query to see if you perhaps are missing a zipcode..also oraCmd.ExecuteScalar() returns only 1 row so make sure you are not returning more than one row..oracle is funny like that
change your code to the following
object bExists = oraCmd.ExecuteScalar();
var bexists = bExists != DBNull.Value && result != null;
or change your code to check for row.count > 0 if true then you know the zipcode was found. Remember when making changes to Sql scripts or stored procedures in Oracle, you need to Compile the changes otherwise the changes will be visible to you when looking at the code but not to the caller trying to execute the stored proc.

how to pass an optional parameter to sql function from C#

I have an issue. please help to solve my problem
I have a SQL function
function [dbo].[fnKudishikaAmt]
(#ParishName nvarchar(100), #Hno int, #dateto datetime = Null)
Returns Decimal(15,2)
This function shows proper result by using the execute command
Select dbo.fnKudishikaAmt('St.George Malankara Catholic Church', 29, default)
My requirement is this function should be called from C#
I am getting the error
Conversion failed when converting datetime from character string
Code:
public double kudishikatotal(string ParishName, Int32 HouseNo)
{
String SQLText = "select ChurchDB.dbo.fnKudishikaAmt(#ParishName, #Hno, #dateto) as fnresult";
SqlCommand cmd = new SqlCommand(SQLText);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ParishName", ParishName);
cmd.Parameters.AddWithValue("#Hno", HouseNo);
cmd.Parameters.AddWithValue("#dateto", "default");
string rval = GetSingleValue(cmd);
double kudiamt = 0;
if (rval != null)
{
kudiamt = Convert.ToDouble(rval);
}
return kudiamt;
}
private static string GetSingleValue(SqlCommand cmd)
{
string ConString = connectionstring();
string returnvalue = "";
using (SqlConnection con = new SqlConnection(ConString))
{
cmd.Connection = con;
con.Open();
returnvalue = cmd.ExecuteScalar().ToString();
con.Close();
}
return returnvalue;
}
If you've declared default value for parameter in stored procedure - then you can just not pass this parameter from c# code at all, and in this case it will have default value.
In your case exception thrown because it's impossible to convert string "default" to SqlDateTime which is your parameter type.
YOu can use if condition while sending the datetime parameter.
if(some condition)
{
cmd.Parameters.AddWithValue("#dateto", dateTimeValue);
}
Here datetimeValue is the value you want to pass. So you will be passing dateTimeValue only if required.
The error is due to the string "default" you passed.

Handling ExecuteScalar() when no results are returned

I am using the following SQL query and the ExecuteScalar() method to fetch data from an Oracle database:
sql = "select username from usermst where userid=2"
string getusername = command.ExecuteScalar();
It is showing me this error message:
System.NullReferenceException: Object reference not set to an instance of an object
This error occurs when there is no row in the database table for userid=2.
How should I handle this situation?
According to MSDN documentation for DbCommand.ExecuteScalar:
If the first column of the first row in the result set is not found, a
null reference (Nothing in Visual Basic) is returned. If the value in
the database is null, the query returns DBNull.Value.
Consider the following snippet:
using (var conn = new OracleConnection(...)) {
conn.Open();
var command = conn.CreateCommand();
command.CommandText = "select username from usermst where userid=2";
string getusername = (string)command.ExecuteScalar();
}
At run-time (tested under ODP.NET but should be the same under any ADO.NET provider), it behaves like this:
If the row does not exist, the result of command.ExecuteScalar() is null, which is then casted to a null string and assigned to getusername.
If the row exists, but has NULL in username (is this even possible in your DB?), the result of command.ExecuteScalar() is DBNull.Value, resulting in an InvalidCastException.
In any case, the NullReferenceException should not be possible, so your problem probably lies elsewhere.
First you should ensure that your command object is not null. Then you should set the CommandText property of the command to your sql query. Finally you should store the return value in an object variable and check if it is null before using it:
command = new OracleCommand(connection)
command.CommandText = sql
object userNameObj = command.ExecuteScalar()
if (userNameObj != null)
string getUserName = userNameObj.ToString()
...
I'm not sure about the VB syntax but you get the idea.
I just used this:
int? ReadTerminalID()
{
int? terminalID = null;
using (FbConnection conn = connManager.CreateFbConnection())
{
conn.Open();
FbCommand fbCommand = conn.CreateCommand();
fbCommand.CommandText = "SPSYNCGETIDTERMINAL";
fbCommand.CommandType = CommandType.StoredProcedure;
object result = fbCommand.ExecuteScalar(); // ExecuteScalar fails on null
if (result.GetType() != typeof(DBNull))
{
terminalID = (int?)result;
}
}
return terminalID;
}
The following line:
string getusername = command.ExecuteScalar();
... will try to implicitly convert the result to string, like below:
string getusername = (string)command.ExecuteScalar();
The regular casting operator will fail if the object is null.
Try using the as-operator, like this:
string getusername = command.ExecuteScalar() as string;
sql = "select username from usermst where userid=2"
var _getusername = command.ExecuteScalar();
if(_getusername != DBNull.Value)
{
getusername = _getusername.ToString();
}
Check out the example below:
using System;
using System.Data;
using System.Data.SqlClient;
class ExecuteScalar
{
public static void Main()
{
SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText ="SELECT COUNT(*) FROM Employee";
mySqlConnection.Open();
int returnValue = (int) mySqlCommand.ExecuteScalar();
Console.WriteLine("mySqlCommand.ExecuteScalar() = " + returnValue);
mySqlConnection.Close();
}
}
from this here
SQL NULL value
equivalent in C# is DBNull.Value
if a NULLABLE column has no value, this is what is returned
comparison in SQL: IF ( value IS NULL )
comparison in C#: if (obj == DBNull.Value)
visually represented in C# Quick-Watch as {}
Best practice when reading from a data reader:
var reader = cmd.ExecuteReader();
...
var result = (reader[i] == DBNull.Value ? "" : reader[i].ToString());
In my experience, there are some cases the returned value can be missing and thus execution fails by returning null. An example would be
select MAX(ID) from <table name> where <impossible condition>
The above script cannot find anything to find a MAX in. So it fails. In these such cases we must compare the old fashion way (compare with C# null)
var obj = cmd.ExecuteScalar();
var result = (obj == null ? -1 : Convert.ToInt32(obj));
If you either want the string or an empty string in case something is null, without anything can break:
using (var cmd = new OdbcCommand(cmdText, connection))
{
var result = string.Empty;
var scalar = cmd.ExecuteScalar();
if (scalar != DBNull.Value) // Case where the DB value is null
{
result = Convert.ToString(scalar); // Case where the query doesn't return any rows.
// Note: Convert.ToString() returns an empty string if the object is null.
// It doesn't break, like scalar.ToString() would have.
}
return result;
}
Always have a check before reading row.
if (SqlCommand.ExecuteScalar() == null)
{
}
This is the easiest way to do this...
sql = "select username from usermst where userid=2"
object getusername = command.ExecuteScalar();
if (getusername!=null)
{
//do whatever with the value here
//use getusername.toString() to get the value from the query
}
In your case either the record doesn't exist with the userid=2 or it may contain a null value in first column, because if no value is found for the query result used in SQL command, ExecuteScalar() returns null.
Alternatively, you can use DataTable to check if there's any row:
SqlCommand cmd = new SqlCommand("select username from usermst where userid=2", conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
string getusername = "";
// assuming userid is unique
if (dt.Rows.Count > 0)
getusername = dt.Rows[0]["username"].ToString();
private static string GetUserNameById(string sId, string connStr)
{
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr);
System.Data.SqlClient.SqlCommand command;
try
{
// To be Assigned with Return value from DB
object getusername;
command = new System.Data.SqlClient.SqlCommand();
command.CommandText = "Select userName from [User] where userid = #userid";
command.Parameters.AddWithValue("#userid", sId);
command.CommandType = CommandType.Text;
conn.Open();
command.Connection = conn;
//Execute
getusername = command.ExecuteScalar();
//check for null due to non existent value in db and return default empty string
string UserName = getusername == null ? string.Empty : getusername.ToString();
return UserName;
}
catch (Exception ex)
{
throw new Exception("Could not get username", ex);
}
finally
{
conn.Close();
}
}
Slight conjecture: if you check the stack for the exception, it is being thrown then the ADO.NET provider for Oracle is reading the underlying rowset to get the first value.
If there is no row, then there is no value to find.
To handle this case execute for a reader and handle Next() returning false for the case of no match.
I Use it Like This with Microsoft Application Block DLL (Its a help library for DAL operations)
public string getCopay(string PatientID)
{
string sqlStr = "select ISNULL(Copay,'') Copay from Test where patient_id=" + PatientID ;
string strCopay = (string)SqlHelper.ExecuteScalar(CommonCS.ConnectionString, CommandType.Text, sqlStr);
if (String.IsNullOrEmpty(strCopay))
return "";
else
return strCopay ;
}
I have seen in VS2010
string getusername = command.ExecuteScalar();
gives compilation error,
Cannot implicitly convert type object to string.
So you need to write
string getusername = command.ExecuteScalar().ToString();
when there is no record found in database it gives error
Object reference not set to an instance of an object
and when I comment '.ToString()', it is not give any error. So I can say ExecuteScalar not throw an exception. I think anserwer given by #Rune Grimstad is right.
I had this issue when the user connecting to the database had CONNECT permissions, but no permissions to read from the database. In my case, I could not even do something like this:
object userNameObj = command.ExecuteScalar()
Putting this in a try/catch (which you should probably be doing anyway) was the only way I could see to handle the insufficient permission issue.
object objUserName;
objUserName = command.ExecuteScalar();
if (objUserName == null) //if record not found ExecuteScalar returns null
{
return "";
}
else
{
if (objUserName == DBNull.Value) //if record found but value in record field is null
{
return "";
}
else
{
string getusername = objUserName.ToString();
return getusername;
}
}
/* Select some int which does not exist */
int x = ((int)(SQL_Cmd.ExecuteScalar() ?? 0));
I used this in my vb code for the return value of a function:
If obj <> Nothing Then
Return obj.ToString()
Else
Return ""
End If
Try this code, it appears to solve your problem.
Dim MaxID As Integer = Convert.ToInt32(IIf(IsDBNull(cmd.ExecuteScalar()), 1, cmd.ExecuteScalar()))
I'm using Oracle.
If your sql returns numeric value, which is int, you need to use Convert.ToInt32(object). Here is the example below:
public int GetUsersCount(int userId)
{
using (var conn = new OracleConnection(...)){
conn.Open();
using(var command = conn.CreateCommand()){
command.CommandText = "select count(*) from users where userid = :userId";
command.AddParameter(":userId", userId);
var rowCount = command.ExecuteScalar();
return rowCount == null ? 0 : Convert.ToInt32(rowCount);
}
}
}
Try this
sql = "select username from usermst where userid=2"
string getusername = Convert.ToString(command.ExecuteScalar());

Categories

Resources