SqlCommand read one value - c#

I have a problem with the value returned from SqlCommand, I have this code:
string sqlSelect = "Select TOP 1 Quotation.SentToSupp as SentToSupp FROM Quotation JOIN Notifications ON Quotation.QuotationId = QuotationID ";
SqlCommand Comm = new SqlCommand(sqlSelect, this.Connection);
sqlSelect query selects the first DateTime value. When I call to SqlCommand I want to get this value (just one value). I add the query and my connection fine.
But I don't know how to get my DateTime value... Must to use something like ExecuteReader?
Thank you in advance!!

ExecuteReader works but more objects and more code are required - (An SqlDataReader, call to Read and Extract value). Instead you could simply use the ExecuteScalar method of the SqlCommand object (It returns just the first column of the first row of the resultset)
string sqlSelect = "Select TOP 1 Quotation.SentToSupp as SentToSupp FROM ....";
SqlCommand Comm = new SqlCommand(sqlSelect, this.Connection);
object result = Comm.ExecuteScalar();
if(result != null)
DateTime dtResult = Convert.ToDateTime(result);
Just pay attention to the fact that ExecuteScalar could return a null value if, for some reason, there is no record in the result returned

Use SqlCommand.ExecuteScalar method - Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

Related

C# MySQL Order By Returns -1

I'm trying to get the last row of a table using C# but it doesn't seem to be working, this is my code:
MySqlConnection cnnGetID = new MySqlConnection(Global.connectionString);
cmd = "SELECT ContactID FROM Contacten ORDER BY ContactID DESC LIMIT 1";
MySqlCommand cmdGetID = new MySqlCommand(cmd, cnnGetID);
cnnGetID.Open();
string contactID = cmdGetID.ExecuteNonQuery().ToString();
MessageBox.Show(contactID);
cnnGetID.Close();
The value this returns is -1 while it should be returning 59.
The strange thing is is that when I run this command in phpmyadmin I DO get 59.
Any ideas on why C# is not returning the correct value but phpmyadmin is?
EDIT: problem solved, should've uses ExecuteScalar(). Looks like I've been staring at my monitor for a bit too long...
You need to use ExecuteScalar instead of ExecuteNonQuery.
MySqlConnection cnnGetID = new MySqlConnection(Global.connectionString);
cmd = "SELECT ContactID FROM Contacten ORDER BY ContactID DESC LIMIT 1";
MySqlCommand cmdGetID = new MySqlCommand(cmd, cnnGetID);
cnnGetID.Open();
string contactID = cmdGetID.ExecuteScalar().ToString();
MessageBox.Show(contactID);
cnnGetID.Close();
This should resolve your issue.
The value this returns is -1 while it should be returning 59.
No, it's behaving exactly as documented by IDbCommand.ExecuteNonQuery:
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1.
You're using a SELECT statement - a query. So instead of executing ExecuteNonQuery, you should be using ExecuteQuery and iterating over the results, or ExecuteScalar, given that you know you'll have a single result:
string contactID = cmdGetID.ExecuteScalar().ToString();
you should use ExecuteScalar because you are returning value ExecuteNonQuery returns the number of rows affected by update delete or insert opeation
you can check this for more info
ExecuteNonQuery
Returns the number of rows affected.
ExecuteScalar
Executes the query, and returns the first column of the first row in
the result set returned by the query. Additional columns or rows are
ignored.
for more information you can check this The MySqlCommand Object
you can use query like this
MySqlConnection cnnGetID = new MySqlConnection(Global.connectionString);
cmd = "SELECT TOP 1 ContactID FROM Contacten ORDER BY ContactID";
MySqlCommand cmdGetID = new MySqlCommand(cmd, cnnGetID);
cnnGetID.Open();
string contactID = cmdGetID.ExecuteNonQuery().ToString();
MessageBox.Show(contactID);
cnnGetID.Close();

SQL execute scalar returning NULL

queryShelf = "SELECT * FROM shelftable WHERE ShelfId= #ShelfId";
//Create Mysql Command
MySqlCommand cmd = new MySqlCommand(queryShelf, connection);
cmd.Parameters.Add(new MySqlParameter("#ShelfId", MySqlDbType.VarChar)).Value = MainWindow.shelfIds[i];
//ExecuteScalar will return one value
int Count = int.Parse(cmd.ExecuteScalar() + "");
ExecuteScalar is used to return a single value, you are selecting complete records. So normally you use ExecuteReader and use Read to get all records.
But actually you can use ExecuteScalar with SELECT *. What happens is that the first column of the first row in the result set is returned, or a null reference if the result set is empty.
Since you get NULL it seems that the filter doesn't return a record.
Since you want a count you could change your query to:
queryShelf = "SELECT COUNT(*) FROM shelftable WHERE ShelfId= #ShelfId";
// ...
int Count = (int) cmd.ExecuteScalar();
Now you never get null but the count of records, 0 if no record exists with this ShelfId.

How to convert data in command object to DateTime?

DateTime DT1;
SqlCommand cmd = new SqlCommand("Select DateReceivedProviderInvoice from ProviderInvoices");
now how to assing the result of the query to DateTime variable DT1?!!!!
You can use SqlCommand.ExecuteScalar Method if you want to get a single value from a column.
SqlCommand.ExecuteScalar: Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
DT1 = Convert.ToDateTime(cmd.ExecuteScalar());

How to get string value from an OracleParameter object when using ExecuteNonQuery

As the code Shows below, I want to insert a row into a database table (oracle 11) and return a String-Value of the inserted row.
using (OracleCommand cmd = con.CreateCommand()) {
cmd.CommandText = "insert into foo values('foo','bar') returning idString into :lastIdParam";
cmd.Parameters.Add(new OracleParameter("lastIdParam", OracleDbType.Varchar2), ParameterDirection.ReturnValue);
cmd.ExecuteNonQuery(); // returning 1 (insert row successfully)
var result = cmd.Parameters["lastIdParam"].Value.ToString(); // == String.Empty
}
Debugging shows that lastIdParam.Value's value = Empty.String:
My Problem is, that I'm not getting the return string into my return-parameter but it will work when returning an integer value (like sequence no of inserted id). Cast Problem? ...?
The idString is filled if running the Statement directly (or if I just do something like returning 'ABC' into :myOutputParameter
Any ideas how to retrieve a string after inserting row?
Have you tried setting a size for the parameter? The default size is 0.
new OracleParameter("lastIdParam", OracleDbType.Varchar2, 128)
The idString is an expression which has no value in your context, unless it is a column name in your table. Therefore, it is epected to be empty. You may change your query like the example below and see what happens.
cmd.CommandText = "insert into foo values('foo','bar') returning hereYouHaveToUseAColumnFromTheFooTable into :lastIdParam";

ExecuteScalar throws NullReferenceException when calling a stored proc that returns 1

I've done some research before posting this question and I'm aware of the fact that when there's no data returned, ExecuteScalar will throw a System.NullReferenceException. That is why I modified my stored proc to "return 1" so there's guaranteed a return value. However, I'm still getting the NULL reference exception.
So I tried to use the SqlCommand to query a table that has data:
SqlCommand sqlCommand = new SqlCommand("SELECT * FROM ATableThatHasValues", conn)
When I ran execute scalar I was able to pick up a value so I know I have permission to query the database. I'm suspecting that this is some specific storeed proc permission setting that I missed?
I'd really appreciate any comment/suggestions as I've been stuck on this for a day now. :(
My code looks like this:
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
using (SqlCommand sqlCommand = new SqlCommand("GetSomeValue", sqlConnection))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
//sqlCommand.Parameters.Add(new SqlParameter("#Id", this.ID));
//sqlCommand.Parameters.Add(new SqlParameter("#State", 1 /* active */));
byte retValue = (byte)sqlCommand.ExecuteScalar();
return retValue;
}
}
THANKS!
I'm just going to elaborate on what #gbn said. When you execute SQL code you can return information in three different ways, OUTPUT parameters, tabular data and/or a single RETURN value. Like #gbn said, RETURN values are essentially specialized OUTPUT parameters. ExecuteScalar only sees information from tabular data, namely the first column of the first row. If no tabular data is received when you call ExecuteScalar a null value is returned instead. If you try to do something with this null value then obviously you'll get a NRE.
Random guess
You are using RETURN so there is no dataset to read column 1, row 1 for ExecuteScalar
Use SELECT or OUTPUT parameters
Edit: Actually, not so random
RETURN 1 is not a result set: it's a "special" parameter
sqlCmd.Parameters.Add(New SqlParameter("RETURN_VALUE", SqlDbType.Int)).Direction = ParameterDirection.ReturnValue

Categories

Resources