MySQL select now() - c#

I'm trying to get time from my database.
string result;
using (MySqlConnection connection = new MySqlConnection("Server=localhost;Database=database;Uid=root;Pwd='';"))
{
string sql = "select now()";
MySqlCommand cmd = new MySqlCommand(sql, connection);
connection.Open();
result = (string)cmd.ExecuteScalar();
connection.Close();
}
DateTime now = DateTime.ParseExact(result, "yyyy-MM-dd HH:mm:ss", null);
metroLabel4.Text = (newtime);
This is the code I'm using and when I build my program It gives error for result = (string)cmd.ExecuteScalar(); this line.

Looks like MySQL Now() returns date and time and this type mapped with DateTime in .NET side.
Since ExecuteScalar returns object, you can explicitly cast it to DateTime and it should be fine.
DateTime result;
...
result = (DateTime)cmd.ExecuteScalar();
A few things more;
Use using statement to dispose your command as well.
Since you use using statement, your connection.Close() line is unnecessary. That statement close your connection automatically.
You don't need parsing anymore. Just assing DateTime now = result;
It is not clear what is newtime exactly but after that, you can assign it as metroLabel4.Text = now.ToString() or whatever you format with ToString(string) overload.

Related

Incorrect syntax near 'datetime'. : 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

I get this error:
Incorrect syntax near 'datetime'.
when running this code of mine:
private static string connectionString = "Data Source=1.1.1.1;Initial Catalog=rs;User Id=rs;Password=rs";
public static List<Cal> getEvents(DateTime start, DateTime end)
{
List<CalendarEvent> events = new List<CalendarEvent>();
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("SELECT [ID], [Name], [Room], [Time-in], [Time-out] FROM [rs].[dbo].[res_time] WHERE [Time-in]>=[#Time-in] AND [Time-out]<=[#Time-out]", con);
cmd.Parameters.AddWithValue("[#Time-in]", start);
cmd.Parameters.AddWithValue("[#Time-out]", end);
using (con)
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
CalendarEvent ce = new CalendarEvent();
ce.id = (int)reader["id"];
ce.title = (string)reader["Name"];
ce.description = (string)reader["Room"];
ce.start = (DateTime)reader["Time-in"];
ce.end = (DateTime)reader["Time-out"];
events.Add(cevent);
}
}
return events;
}
The AddWithValue() method can be problematic for dates and times. Use
cmd.Parameters.Add("[#Time-in]", SqlDbType.DateTime).Value = start;
cmd.Parameters.Add("[#Time-out]", SqlDbType.DateTime).Value = end;
You can read this article for more information on the limitations of the AddWithValue() method. The gist of it is that since it has to infer the correct data type, sometimes it gets is wrong. This is especially true for dates and times.
Using this overload of the Add() method specifies the exact data type that was declared when the column was created on the table, helping to ensure that the correct type is resolved.
Firstly, are you trying to return a List<Cal> or a List<CalenderEvent>?
To answer your question, you need to parse it manually in Visual Studio
ce.start = Convert.ToDateTime(reader["Time-in"]).ToString();
This is assuming that your column data is in the proper format for the conversion to work.
UPDATE:
Ok I screwed up my .ToString()
Try this one:
// I moved the .ToString() inside the Convert function
ce.start = Convert.ToDateTime(reader["Time-in"].ToString());
You're getting the implicit conversion error because its applying the .ToString() AFTER the parse which means you're trying to put a string value into a DateTime variable. My bad!

String was not recognized as valid Datetime after converting Db from MSSQL to SQLite

While playing with a code originally written for MSSQL ,i changed it to SQLite ,working well when it broke down to saying after icommand.ExecuteNonQuery();.
String was not recognized as valid Datetime
try
{
using (SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MMIS.sqlite;Version=3;"))
{
String query = "INSERT INTO tbl_Mdcl (Invoice_No,Invoice_Date,CustomerId,Med_Name,Comp_Name,Date_Manaf,Date_Exp,Qty,Price,Discount,Retail) VALUES (#Invoice_No,#Invoice_Date,#CustomerId,#Med_Name,#Comp_Name,#Manaf_Date,#Exp_Date,#Qty,#Price,#Discount,#Retail)";
m_dbConnection.Open();
using (SQLiteCommand icommand = new SQLiteCommand(query, m_dbConnection))
{
////a shorter syntax to adding parameter
icommand.Parameters.Add("#Invoice_No", System.Data.DbType.Int32).Value = InvoiceNo.Text.ToString();
icommand.Parameters.Add("#Invoice_Date", System.Data.DbType.Date).Value = dateTimePicker1.Value.ToString();
icommand.Parameters.Add("#CustomerId", System.Data.DbType.Int32).Value = PartId.Text;
icommand.Parameters.Add("#Med_Name", System.Data.DbType.String).Value = combomedicine.Text;
icommand.Parameters.Add("#Comp_Name", System.Data.DbType.String).Value = combocompany.Text;
icommand.Parameters.Add("#Manaf_Date", System.Data.DbType.Date).Value = dateTimePicker2.Value.ToString();
icommand.Parameters.Add("#Exp_Date", System.Data.DbType.Date).Value = dateTimePicker3.Value.ToString();
icommand.Parameters.Add("#Qty", System.Data.DbType.Int32).Value = qty.Text;
icommand.Parameters.Add("#Price", System.Data.DbType.Int32).Value = totl_prc;
icommand.Parameters.Add("#Discount", System.Data.DbType.Int32).Value = totldsc;
icommand.Parameters.Add("#Retail", System.Data.DbType.Int32).Value = retailpric;
var rowsaffected = icommand.ExecuteNonQuery();
MessageBox.Show("Record inserted. Please check your table data. :)");
ShowListView();
}
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
The same code while having SqlDbType.Date as the second parameter of icommand.Parameters.Add(,) worked well while changing it to System.Data.DbType.Date messed it.I'm at loss even after consulting the documentation for System.Data.DbType.Date.
All other tweaks are working right now.
PS.The columns are set to Date im Db so no question of Datetime
If the parameter is of type date, why do you send a string as value? as far as I rememver, DateTimePicker.Value is of type DateTime. try it without the ToString() and see if that helps.
If not, use the ToString to provide a known format and use CONVERT in the INSERT statement for this format. example:
String query = "INSERT INTO TableName(DateColumn) VALUES (CONVERT(Date, #DateValue, 103)"; // 103 is this format: dd/mm/yyyy
SqlParameter DateParam = new SqlParameter("#Invoice_Date", System.Data.DbType.Char, 10);
DateParam.Value = dateTimePicker1.Value.ToString("dd/MM/yyyy");
icommand.Parameters.Add(DateParam);

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

How to run query on date time colomn

Trying to retrieve records by passing date in where condition, i am sending date by using date time picker but at the end reader not showing any record.
I did conversion of date time as Convert(char(10),ext_date,101) still facing the same problem.
string str=#"select * from extra_expense where CONVERT(char(10),ext_date,101) = #date";
sqlcommand = new SqlCommand(str,sqlconnection );
sqlcommand.Parameters.Add("#date", SqlDbType.DateTime).Value = datetimepicker1.value);
datareader = sqlcommand.ExecuteReader();
List<Projects> projects = new List<Projects>();
while (datareader.Read())
{
Projects proj = new Projects();
proj.expenseid = Convert.ToInt32(datareader.GetValue(0));
proj.ProjectDate = Convert.ToDateTime(datareader.GetValue(1));
projects.Add(proj);
}
datareader.Close();
return projects;
You can specify dates as strings in T-SQL, like so:
SELECT MyFields FROM MyTable
WHERE StartDate >= '01-01-00' AND StartDate <= '12-31-00'
You shouldn't cast the field in the table, you should cast the parameter to the correct type. In fact, you are already casting it because the parameter is declared as datetime, but on your query you are forcing ext_date to char(10).
Try this:
string str=#"select * from extra_expense where ext_date = #date";
along with
sqlcommand.Parameters.Add("#date", SqlDbType.DateTime).Value = datetime.Parse( datetimepicker1.value);

Compare Datetime.now to date on SQL table

I'm trying to write code on c# that will compare between date that i have on SQL table (table:items, column "endTime") against datetime.now and by the result - display image.
example:
if the time on the column table is before the time now.. so display on the aspx image1, else display image2.
i've tried to do that by sql command:
private DateTime endTime(out int lastDate)
{
SqlConnection connection = new SqlConnection("Data Source=******;Initial Catalog=******;User ID=*****;Integrated Security=False;");
string commandtext = "SELECT TOP(1) endTime FROM items";
SqlCommand command = new SqlCommand(commandtext, connection);
connection.Open();
SqlCommand command2 = new SqlCommand(commandtext, connection);
lastDate = (int)command2.ExecuteScalar();
connection.Close();
return ...
}
but i have problem with the return, and with the execution of the method... :
int d;
Console.WriteLine(endTime(out d));
if (d < DateTime.Now)
{
image1.Visible = true;
}
else
{
image2.Visible = true;
}
Console.WriteLine(d);
but i got error, but i believe it's come from the return.
Instead of if (d < DateTime.Now) use this: if (d < DateTime.Now.Date)
Shouldn't you be casting out a DateTime from your query and not an int? Also, the stack trace/debugger should give you the line number of the exception. Can you post the stack trace?
What is returned by your sql query (I believe ticks)?
How do you convert int into DateTime, show a code please
Enclose SqlConnection in using() block as shown below:
using (SqlConnection connection = new SqlConnection(...))
i would suggest letting the database do the date comparison right in the sql.
SYSDATE can be compared to EndTime right in the query, and you can either not bring back rows that dont match (which allows you to process every row in the result set equally) or you check a simple value in the return set to see if the time is in the right period.

Categories

Resources