when i trying the same query on Oracle SQL develloper:
select nom_projet from analyses where nom_projet='demonstration';
it works, so i very don't know where could come the error...
I think it's due to the format of my request but i don't see the error.
Code C#
public Boolean VerifierVersionDejaPresnte(ParseurXML.DonneesGlobales donneGlobale)
{
string sql = "select nom_projet from analyses where nom_projet = :nom_projet" ;
OracleCommand cmd = new OracleCommand(sql, conn);
cmd.CommandType = CommandType.Text;
OracleParameter p_nom_projet = new OracleParameter();
p_nom_projet.OracleDbType = OracleDbType.Varchar2;
p_nom_projet.Value = donneGlobale._nomProjet;
cmd.Parameters.Add(p_nom_projet);
OracleDataReader dr = cmd.ExecuteReader();
if(dr.Read())
Console.WriteLine(dr.GetString(0));
return (true);
}
Thank you in advance for you help
The most likely cause is that the query returns no data, so dr.Read() returns false. You should always check the result of dr.Read() before trying to access the data.
if (dr.Read())
{
Console.WriteLine(dr.GetString(0));
}
Of course, it doesn't completely solve the issue... now you must find why the query returns nothing.
Related
I'm new in Oracle and trying to execute the next SQL request using C#
try
{
connection.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = connection;
cmd.CommandText = "select count(*) from agreements";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
}
I've read Oracle documentation, I've tried to use
var response = dr.GetString(0);
But it always returns exception
Specified cast is not valid.
Does somebody know how I can solve it ? Thanks for your answers!
Given that you're querying count(*), you'd be better using ExecuteScalar rather than ExecuteReader(), for one thing. Next, the result will be an integer, which is why GetString() fails.
Change it to:
int count = (int) cmd.ExecuteScalar();
(I'd also strongly advise using using statements for your connection, command, and any readers you'd normally create.)
I'm working on one program that I need to modify a little. There's one SQL statement I don't understand what it does (or basically how it does it).
string query = "SELECT dbo.BusinessMinutes(#start,#end,#priorityid)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#start", SqlDbType.DateTime).Value = start;
cmd.Parameters.Add("#end", SqlDbType.DateTime).Value = end;
cmd.Parameters.Add("#priorityid", SqlDbType.UniqueIdentifier).Value = priorityId;
SqlDataAdapter READER = new SqlDataAdapter();
READER.SelectCommand = cmd;
DataTable table = new DataTable();
READER.Fill(table);
if (table.Rows.Count == 1)
{
minutes = (int)table.Rows[0][0];
}
So can someone explain me the SELECT statement there. The end result (minutes) is as expected so it works but that syntax confuses me. Is this somehow equal to SELECT * FROM dbo.BusinessMinutes WHERE...
Is this commonly used and does this syntax has some special name so I could name my question better? Thank you in advance.
dbo.BusinessMinutes has to be a UDF (User Defined Function) that returns a simple scalar value based on a starting date, an ending date and a priority indicator.
Scalar functions, be it UDF or native, can be used in a SELECT statement to produce a field in the returned resultset. Thus, the code you have is perfectly legal.
For more information about scalar UDF, read this MSDN article.
As a side note, a better implementation for that code would be this:
string query = "SELECT dbo.BusinessMinutes(#start,#end,#priorityid)";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.Add("#start", SqlDbType.DateTime).Value = start;
cmd.Parameters.Add("#end", SqlDbType.DateTime).Value = end;
cmd.Parameters.Add("#priorityid", SqlDbType.UniqueIdentifier).Value = priorityId;
// assuming connection is already open
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read()) minutes = reader.GetInt32(0);
}
}
If all you want is to init the minutes variable, using SqlDataReader will be more efficient and performant than creating a SqlDataAdapter and a DataTable. The using statements will also make sure your SqlCommand and SqlDataReader objects gets disposed of properly.
It is not a table name. I think you call into a FUNCTION.
how to create and call scalar function in sql server 2008
has more explanations and examples.
OpenSqlConnection();
SqlCommand cmd = new SqlCommand("ReturnCharacterInfo", Con);
cmd.Parameters.AddWithValue("#CharacterID", CharacterID);
SqlDataReader dr = cmd.ExecuteReader();
When I run code you can see above, it throws exception
Procedure or function 'ReturnCharacterInfo' expects parameter '#CharacterID', which was not supplied.
but as you can see at the code, I'm suppying #CharacterID parameter and it's not empty or null.
Stored procedure:
[ReturnCharacterInfo] #CharacterID int
as
select
CharacterName, characterSurname, CharacterIsMale, CharacterAge,
CharacterMood, CharacterHealth, CharacterInCity, CharacterInLocation,
Cities.CityName, Locales.LocaleTitle
from
Characters
INNER JOIN
Cities on Cities.CityID = Characters.CharacterInCity
INNER JOIN
Locales on Locales.LocaleID = Characters.CharacterInLocation
Where
CharacterID = #CharacterID
Any suggestions?
I would try to explicitly specifying the type of the parameter - especially important if the value is null:
SqlCommand cmd = new SqlCommand("ReturnCharacterInfo", Con);
// added as per CodeNaked's comment - thanks! You've nailed it right on the head!
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#CharacterID", SqlDbType.Int).Value = CharacterID;
Also: do you have a typo anywhere?? Triple-check all occurrences of CharacterID - do you happen to have CharachterID or something like that somewhere in your code??
As CodeNaked pointed out, you need to set the command type of the SqlCommand. The SqlCommand object needs to be told it's a stored procedure because of the way that stored procedures are executed.
OpenSqlConnection();
SqlCommand cmd = new SqlCommand("ReturnCharacterInfo", Con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CharacterID", CharacterID);
SqlDataReader dr = cmd.ExecuteReader();
I have a procedure on Oracle that works perfectly fine if I call it from SQL Developer using this code:
VARIABLE x REFCURSOR
exec MY_PROCEDURE('par1', 'par2', 'par3', 'par4' ,:x);
PRINT x;
If I try to call it form my .Net app (using ODP.NET), I get the error:
Oracle.DataAccess.Client.OracleException ORA-08103: object no longer exists
This is the code I use to call it:
OracleConnection con = new OracleConnection();
con.ConnectionString = dbConnectionString; //string with the connectio. It is fine because I can connect
OracleCommand cmd = new OracleCommand("MY_PROCEDURE", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.Add(new OracleParameter("par1", OracleDbType.Varchar2)).Value = var1;
cmd.Parameters.Add(new OracleParameter("par2", OracleDbType.Varchar2)).Value = var2;
cmd.Parameters.Add(new OracleParameter("par3", OracleDbType.Varchar2)).Value = var3;
cmd.Parameters.Add(new OracleParameter("par4", OracleDbType.Varchar2)).Value = var4;
OracleParameter ref_cursor = new OracleParameter();
ref_cursor.OracleDbType = OracleDbType.RefCursor;
ref_cursor.Direction = ParameterDirection.Output;
cmd.Parameters.Add(ref_cursor);
con.Open();
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{ ... }
The cmd.ExecuteReader command actually "works", the application exception is thrown on the dr.read but If I check the dr object, on the hasRows property I can see the ORA-08103: object no longer exists error.
What can be wrong?
One detail is that I have a similar procedure that follows pretty much the same logic (of returing a cursor) and works fine.
Does the query for the returned cursor involve temporary tables? You can shoot yourself in the foot if you return a cursor involving temporary tables with the ON COMMIT DELETE ROWS options and then commit the transaction before you have retrieved the cursor data.
The COMMIT easily happens because ODP.NET by default works in auto commit mode.
To fix it,
either turn off auto commit,
or use temporary tables with the ON COMMIT PRESERVE ROWS options (instead of ON COMMIT DELETE ROWS),
or use regular tables.
You can also create a Transaction for your connection, and set the transaction in the OracleCommand object.
It will also keep the commits from happening before you retrieve all the data.
Ok either I'm really tired or really thick at the moment, but I can't seem to find the answer for this
I'm using ASP.NET and I want to find the amount of rows in my table.
I know this is the SQL code: select count(*) from topics, but how the HECK do I get that to display as a number?
All I want to do is run that code and if it = 0 display one thing but if it's more than 0 display something else. Help please?
This is what I have so far
string selectTopics = "select count(*) from topics";
// Define the ADO.NET Objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand topiccmd = new SqlCommand(selectTopics, con);
if (topiccmd == 0)
{
noTopics.Visible = true;
topics.Visible = false;
}
but I know I'm missing something seriously wrong. I've been searching for ages but can't find anything.
PHP is so much easier. :)
Note that you must open the connection and execute the command before you can access the result of the SQL query. ExecuteScalar returns a single result value (different methods must be used if your query will return an multiple columns and / or multiple rows).
Notice the use of the using construct, which will safely close and dispose of the connection.
string selectTopics = "select count(*) from topics";
// Define the ADO.NET Objects
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand topiccmd = new SqlCommand(selectTopics, con);
con.Open();
int numrows = (int)topiccmd.ExecuteScalar();
if (numrows == 0)
{
noTopics.Visible = true;
topics.Visible = false;
}
}
ExecuteScalar is what you're looking for. (method of SqlCommand)
Btw, stick with C#, there's no way PHP is easier. It's just familiar.
You need to open the connection
This might work :
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "select count(*) from topics";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
sqlConnection1.Close();
Similar Question: C# 'select count' sql command incorrectly returns zero rows from sql server