I'm trying to change my program from an SqlConnection
to an OleDbConnection
but I've hit a little block.
My program works as expected using SqlConnection
but I can't get it to work with OleDb
.
My program reads the results of a stored procedure (XML), sends it to a web service, then stores the results in a table.
I'm having issues with reading the XML from the stored procedure.
Here's my code for the first part:
public static bool BuildXml()
{
using (OleDbCommand buildXml = new OleDbCommand("usp_BUILD_RISKCALC_XML", SqlOleDbConnection))
{
buildXml.CommandType = CommandType.StoredProcedure;
try
{
OleDbDataReader reader = buildXml.ExecuteScalar();
while (reader.Read())
{
SendXml = reader.GetString(0);
}
}
catch (Exception ex)
{
WriteLog(ex.Message, 101);
return false;
}
}
}
I'm getting an InvalidOperationException
the text of which reads
Specified cast is not valid
For reader.GetString(0)
.
I am 100% sure the stored procedure is working as I have tested using an SqlConnection
as well as running in SQL Server Management Studio.
Your code should be;
public static bool BuildXml()
{
using (OleDbCommand buildXml = new OleDbCommand("usp_BUILD_RISKCALC_XML", SqlOleDbConnection))
{
buildXml.CommandType = CommandType.StoredProcedure;
try
{
object value = buildXml.ExecuteScalar();
SendXml = Convert.ToString(value);
}
catch (Exception ex)
{
WriteLog(ex.Message, 101);
return false;
}
}
}
The code buildXml.ExecuteScalar()
returns an object. So casting it to an OleDbDataReader
will end up in the InvalidOperationException
.
ExecuteScalar
return type's is object
and you can't convert it to OleDbDataReader
. When you have used ExecuteScalar
means that you are sure that you want to return only one value from your stored procedure. You don't need OleDbDataReader
just try following:
SendXml = buildXml.ExecuteScalar().ToString;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.