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.)
Related
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.
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.
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
Why does this return null?
//seedDate is set to DateTime.Now; con is initialized and open. Not a problem with that
using (SqlCommand command = new SqlCommand("fn_last_business_date", con))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#seed_date", seedDate);//#seed_date is the param name
object res = command.ExecuteScalar(); //res is always null
}
But when I call this directly in the DB as follows:
select dbo.fn_last_business_date('8/3/2011 3:01:21 PM')
returns '2011-08-03 15:01:21.000'
which is the result I expect to see when I call it from code
Why, why, why?
Why does everyone insist on the select syntax?..
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("calendar.CropTime", c))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#RETURN_VALUE", SqlDbType.DateTime).Direction = ParameterDirection.ReturnValue;
cmd.Parameters.AddWithValue("#d", DateTime.Now);
cmd.ExecuteNonQuery();
textBox1.Text = cmd.Parameters["#RETURN_VALUE"].Value.ToString();
}
try:
using (SqlCommand command = new SqlCommand("select dbo.fn_last_business_date(#seed_date)", con))
{
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#seed_date", seedDate);//#seed_date is the param name
object res = command.ExecuteScalar(); //res is always null
}
You are actually getting an error that isn't being caught. You don't call scalar udfs like you call stored procedures.
Either wrap the udf in a stored proc, or change syntax. I'm not actually sure what that is because it isn't common...
Ah ha: see these questions:
How to use SQL user defined functions in .NET?
Calling user defined functions in Entity Framework 4
I am getting exception: "Specific cast is not valid", here is the code
con.Open();
string insertQuery = #"Insert into Tender (Name, Name1, Name2) values ('Val1','Val2','Val3');Select Scope_Identity();";
SqlCommand cmd = new SqlCommand(insertQuery, con);
cmd.ExecuteNonQuery();
tenderId = (int)cmd.ExecuteScalar();
In the interests of completeness, there are three issues with your code sample.
1) You are executing your query twice by calling ExecuteNonQuery and ExecuteScalar. As a result, you will be inserting two records into your table each time this function runs. Your SQL, while being two distinct statements, will run together and therefore you only need the call to ExecuteScalar.
2) Scope_Identity() returns a decimal. You can either use Convert.ToInt32 on the result of your query, or you can cast the return value to decimal and then to int.
3) Be sure to wrap your connection and command objects in using statements so they are properly disposed.
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(sql, connection))
{
connection.Open();
int tenderId = (int)(decimal)command.ExecuteScalar();
}
}
Try this:-
con.Open();
string insertQuery = #"Insert into Tender (Name, Name1, Name2) values ('Val1','Val2','Val3');Select Scope_Identity();";
SqlCommand cmd = new SqlCommand(insertQuery, con);
tenderId = Convert.ToInt32(cmd.ExecuteScalar());
EDIT
It should be this as it is correctly pointed out that scope_identity() returns a numeric(38,0) :-
tenderId = Convert.ToInt32(cmd.ExecuteScalar());
Note: You still need to remove the:-
cmd.ExecuteNonQuery();
Test the following first:
object id = cmd.ExcuteScalar()
Set a break point and have a look at the type of id. It is probably a Decimal and cannot directly be casted to int.
it needs Convert.ToInt32(cmd.ExecuteScalar());