How to convert data in command object to DateTime? - c#

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());

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();

OleDbDataAdapter UPDATE query comparing date type with string

I have an OleDbDataAdapter that is doing an UPDATE on a database.
On the table that I am updating I have a column named "Temp_date" that holds dates in the mm/dd/yyyy format.
Is there any way I can compare the string from the table with an actual DateTime (current date)? My purpose is that if the date stored in the table is lower than the current date then to have the old value deleted.I would really appreciate your help or suggestions!
Here is what my code looks like:
OleDbDataAdapter adapter3 = new OleDbDataAdapter();
adapter3.UpdateCommand = conexiuneBD.CreateCommand();
adapter3.UpdateCommand.CommandText = "UPDATE table SET Occupied=No, Temp_date=? WHERE Temp_date<?";
adapter3.UpdateCommand.Parameters.AddWithValue("p1", DBNull.Value);
adapter3.UpdateCommand.Parameters.AddWithValue("p2", current_date);
What about converting the date first and just passing the constant value to compare?
OleDbDataAdapter adapter3 = new OleDbDataAdapter();
adapter3.UpdateCommand = conexiuneBD.CreateCommand();
string convertedDate = ConvertDateToAccessFormat(current_date);
adapter3.UpdateCommand.CommandText = "UPDATE table SET Occupied=No, Temp_date=? WHERE Temp_date<" + convertedDate;
adapter3.UpdateCommand.Parameters.AddWithValue("p1", DBNull.Value);
adapter3.UpdateCommand.Parameters.AddWithValue("p2", current_date);
Or you could make it a two part process. First, get the current value of Temp_date from the database, and only if it is less than your prospective new date would you call the update code.
Or you could use the access string-to-date conversion:
UPDATE table SET Occupied=No, Temp_date=? WHERE cDate(Format(Temp_date,"yyyy-MM-dd hh:mm:ss")) < ?
And BTW, if Temp_date is stored as a string, aren't you going to have to send it in as a string? In that case you'll have to convert both values in order to compare them as dates. Something like this?
UPDATE table SET Occupied=No, Temp_date=? WHERE cDate(Format(Temp_date,"yyyy-MM-dd hh:mm:ss")) < cDate(Format(?,"yyyy-MM-dd hh:mm:ss"))

Should I use datatable to store one column of select query in asp.net

My sql select query will return one column of company names (many rows of names). Now I want to store it. I used:
try
{
connection.Open();
sqlCmd = new SqlCommand(sqlCmd.CommandText, connection);
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Clear();
sqlReader.Read();
dt.Load(sqlReader);
Then I tried to access the name by
dt.Rows[0][0].ToString()
dt.Rows[1][0].ToString()
dt.Rows[2][0].ToString()
etc.
But I recognize that the value in dt.Rows[0][0].ToString() is different from time to time, event if I use the same query, and it looks like that the old values still stored in the datatable event if I use new query value.
How is the right way to store and retrieve values here?
You can use,
string compnay_name = dt.Rows[0]["column_name"].ToString();
Try using your compnay name column in double quote.
You can use it in a for or foreach loop.
as,
for(int i=0;i<count;i++)
{
string compnay_name = dt.Rows[i]["column_name"].ToString();
}
Hope it helps...
Aki

Finding time difference between two times stored in database using sql and c#

string sqlUserName3 = "SELECT out_date FROM status where s_id='" + TextBox2.Text + "'";
SqlCommand sqlcmd3 = new SqlCommand(sqlUserName3, sqlcon);
sqlUserName4 = "SELECT in_date FROM status where s_id='"+TextBox2.Text+"'";
SqlCommand sqlcmd4 = new SqlCommand(sqlUserName4, sqlcon);
string q3 = sqlcmd3.ExecuteNonQuery().ToString();
string q4 = sqlcmd4.ExecuteNonQuery().ToString();
DateTime dt1 = DateTime.Parse(q3);
DateTime dt2 = DateTime.Parse(q4);
TimeSpan result = dt1.Subtract(dt2);
string result1 = result.ToString();
TextBox8.Text = result1;
//Response.Redirect("login.aspx");
sqlcon.Close();
There are many things wrong with your code at the moment:
You shouldn't use string concatenation to build your query. Use parameterized SQL instead. This will avoid SQL injection attacks and conversion issues
You're using ExecuteNonQuery when you're trying to execute... a query.
You're converting the results into a string which is a bad idea even if it did return a date... instead, get the results in a form you can fetch as just a DateTime. Avoid string conversions wherever you can.
So you should:
Use parameters instead of dynamic SQL
Use ExecuteReader and get the first result from each reader
Use the GetDateTime method to get the DateTime from the results.
I would personally use the subtraction operator afterwards, too:
TimeSpan difference = end - start;
... but that's just a matter of preference, and not an actual mistake in your current code.
Your mistake is here:
string q3 = sqlcmd3.ExecuteNonQuery().ToString();
string q4 = sqlcmd4.ExecuteNonQuery().ToString();
DateTime dt1 = DateTime.Parse(q3);
DateTime dt2 = DateTime.Parse(q4);
ExecuteNonQuery does not return a date in a string representation. It returns the number of records affected by the query; hence, when you run DateTime.Parse(number) you get an error.
None of your queries are returning a date so it's unclear how you expect to get a date back from calling the SQL you have in your question...
Update
Do not use string concatenation to build your SQL Statements. You can use parameters to avoid exposing yourself to SQL Injection attacks. One example would be:
string sqlUserName3 = "SELECT out_date FROM status where s_id=#id";
SqlCommand sqlcmd3 = new SqlCommand(sqlUserName3, sqlcon);
sqlcmd3.Parameters.AddWithValue("#id",TextBox2.Text );
You use SqlCommand.ExecuteNonQuery() but you need SqlCommand.ExecuteScalar(). The first function returns nothing, it's supposed to be used for queries like insert or update. The second returns value of first cell of first row of query output.
You should use execute scalar or pass some out parameter to get value. This should get you some value in q3 and q4.
Now to avoid erros you should also use DateTime.ParseExact instead of simple Parse.
DateTime dt1 = DateTime.ParseExact(q3,"dd/mm/yyyy HH:mm",CultureInfo.InvariantCulture);
DateTime dt2 = DateTime.ParseExact(q4,"dd/mm/yyyy HH:mm",CultureInfo.InvariantCulture);

SqlCommand read one value

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.

Categories

Resources