I am trying to insert current time to a Time column in the excel using the below code through an oledb connection but when I check the excel the value inserted is in Date format.
Value updated in excel - 1/0/1900 3:54:11 PM
Expected Value - 3:54:11 PM
string currentTime = DateTime.Now.ToString("hh:mm:ss.fff tt");
string cmnd1 = "Create Table [" + currentDate + "] (TestCase char(100), ExecutionTime Time, Result char(20))";
string cmnd2 = "Insert Into [" + currentDate + "] (TestCase, ExecutionTime, Result) values ("+ "'" + tName + "',#dd,'" + result +"')" ;
using (OleDbConnection conn = new OleDbConnection(ConnectionStringtd))
{
OleDbCommand createSheet = new OleDbCommand(cmnd1, conn);
OleDbCommand insertResult = new OleDbCommand(cmnd2, conn);
insertResult.Parameters.AddWithValue("#dd", DateTime.Now.TimeOfDay);
conn.Open();
try
{
createSheet.ExecuteNonQuery();
}
catch(OleDbException) {}
insertResult.ExecuteNonQuery();
}
}
AFAIK, when you enter pure time value stored as a datetime with the entered time portion, and a date part will be January 0, 1900 automatically since the days before 1900 are incorrect in Excel.
Instead of that, pass your DateTime.Now directly to parameter and change your column format type to Time with h:mm:ss tt format in your format cells part. By the way, you just paramterized #dd part. Use parameters for the other values that you try to insert. Don't concatenate them.
insertResult.Parameters.AddWithValue("#dd", DateTime.Now);
And don't use AddWithValue anymore. It may generate unexpected and suprising results sometimes. Use Add method overload to specify your parameter type and it's size.
Also use using statement to dispose your commands as you did for the connection.
Related
On the server, the date format is mm-dd-yyyy. On my local machine, the date format is mm/dd/yyyy.
I have the following code:
DateTime FrDate, Todate;
string yy = "2020";
string mm = "04";
string dd = "01";
DateTime.TryParse(mm + "/" + dd + "/" + yy, out FrDate);
And then I am trying to run this query:
select * from helpdesk_tranactions where compl_date `= '" + FrDate.ToShortDateString() + "'
This is working fine when I run on my local machine, where the date format is mm/dd/yyyy.
However, when this code is deployed to the server, the same query is not working (since the date format is mm-dd-yyyy).
The error I get is:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
How can I write this query in such a way that it will work regardless of the system date formatting?
Noooooooo! If you're worried about string formats for SQL date values something has already gone horribly wrong.
The column in your database should be a Date, Timestamp, or DateTime rather than varchar field, and if that's true there is no human-readable format! The data is binary. What you see is a convenience shown to you by your management tool or connection library. If you're not using one of the date types for the column column, you should fix the schema, because it really is broken.
Once you have confirmed or fixed the column so you know it is a DateTime value, you should also be using DateTime variables in the C# code. And once you're doing that, the correct way to include those values in a query looks like this (assuming MySql because of the backtick, but you should also tag the question with the correct database engine):
string sql = "select * from helpdesk_tranactions where compl_date = #compl_date";
using (var cn = new MySqlConnection("connection string here"))
using (var cmd = new MySqlCommand(sql, cn))
{
cmd.Parameters.Add("#compl_date", MySqlDbType.DateTime).Value = FrDate;
cn.Open();
// ...
}
Notice this assigns the FrDate field directly to the query parameter. There's no conversion in your code to worry about.
This technique is also the best and only truly safe way to avoid certain other types of problem with sql.
I have 2 project, one is CRUD class and another is contain a WinForm that will access the CRUD class.
Here come my problem, everytime i trying to insert DateTimePicker with default value in MYSQL with datetime column type, i getting 0000-00-00 00:00:00 Zero zero zero and zero value, what i missed here?
Here is my part of CRUD class code, my CRUD class named DBConnect.cs
public DateTime property_dtDate { get; set; }
sqlQuery = "INSERT INTO master (NoInvoice, Name, Date, Type, Additionaltext) VALUES ('" + property_NoInvoice + "', '" + property_sName + "', '" + property_dtDate + "', '" + property_sType + "', '" + property_sAdditionalText + "')";
And here is my part of WinForm code, which is i named it Form1.cs (both is in separated project)
clsDbConnect.property_dtDate = DateTime.Parse(datetimepicker1.Value.ToString("yyyy-MM-dd HH:mm:ss"));
clsDbConnect.Insert();
I try look at the value with messagebox, a value that pass through my WinForm is good, nothing suspicious, it show the every date and time which is right know, but when i looked in my database, all i got is 0000-00-00 00:00:00. I don't have any clue what cause that, help me to find out please
I think you have a problem because of string format of the datetime. MySQL not understand your string format as a datetime value.
Try use parameters(assume somewhere in code you have a SqlCommand object):
string query = "INSERT INTO master (NoInvoice, Name, Date, Type, Additionaltext) VALUES (#NoInvoice, #sName, #dtDate, #sType, #sAdditionalText)";
using(SqlCommand command = New SqlCommand(query, yourconnection)
{
command.Parameters.AddWithValue("#NoInvoice", property_NoInvoice);
command.Parameters.AddWithValue("#sName ", property_sName);
command.Parameters.AddWithValue("#dtDate ", property_dtDate);
command.Parameters.AddWithValue("#sType ", property_sType);
command.Parameters.AddWithValue("#sAdditionalText ", property_sAdditionalText);
command.ExecuteNonQuery();
}
Using parameters help with type safety(datetime and numerics format issues) and prevent a SQL injection vulnerability.
Then when you don't need to parse a datetimepicker's value to type DateTime because ti is already DateTime (From MSDN: DateTimePicker.Value)
clsDbConnect.property_dtDate = datetimepicker1.Value;
I am having a problem with reading DateColumns from an excel sheet.
Sometimes people use different date Formats and this brings a problem. Let's say when I expect 07/26/2010 from an Excel column I get 26-Jul-2010 because the user has changed its date format.
I use Microsoft.Jet.OLEDB for reading the xls sheet into a DataTable.
Can I somehow force OleDb reader whatever the DateFormat is set on XLS, to convert all the dates into MM/DD/YYYY format?
I use this piece of code to read the Excel file:
string strConn;
strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + uploadedFileInfo.FullName + ";" +
#"Extended Properties=""Excel 8.0;HDR=NO;""";
using (OleDbConnection connToExcel = new OleDbConnection(strConn))
{
//You must use the $ after the object you reference in the spreadsheet
connToExcel.Open();
string firstSheetName = ExcelUploadedFileReaderBuilder
.GetFirstExcelSheetName(connToExcel);
OleDbDataAdapter myCommand
= new OleDbDataAdapter(String.Format("SELECT * FROM [{0}]", firstSheetName), connToExcel);
DataSet myDataSet = new DataSet();
myCommand.Fill(myDataSet, "uploadedExcelTable");
DataTable dtUploadedExcel = myDataSet.Tables["uploadedExcelTable"];
lineCount = GetLineNumberWhereNULLRowOccured(dtUploadedExcel) + 1;
connToExcel.Close();
}
You don't have to loop through the dataset as suggested. You can have your query do all the formatting for you by specifying in your query the format you want.
An example is as follows:
OleDbDataAdapter myCommand =
new OleDbDataAdapter("SELECT FORMAT([DateCol], 'MM/dd/yyyy') as [DateCol] FROM [SheetName]", connToExcel);
This is guaranteed to work as long as you're using JET OLEDB or the Ace OLEDB data provider. I cannot guarantee it'll work with other data providers but you can always check.
Loop through the dataset. For each date, covert it to a date (in case the cell has been modified to be text), and then format the date as a string of form "MM/DD/YYYY".
The following code is an example to get you started:
string date1 = "07/26/2010";
string date2 = "26-Jul-2010";
DateTime dt1 = Convert.ToDateTime(date1);
DateTime dt2 = Convert.ToDateTime(date2);
string date1B = dt1.ToString("MM/DD/YYYY");
string date2B = dt2.ToString("MM/DD/YYYY");
date1B and date2B will be equal and in the format that you desire.
There is a bit of back and forth conversion going on and that is because you'll need to validate user input since it is coming from Excel and it is very easy for a user to enter data that won't conform with you database model.
It will be a good idea to put everything in a Try-Catch block in case some of the entered dates are not valid dates themselves.
I was trying to make excel graphs using query in c# and I need to collect data for the last month. I am using the following code and its not giving any error but its not giving any result either.
Basicaly I have the data in excel sheets and using that data im making graphs.
First im geting the two dates and converting them to short string and then im matching the strings with the dates picked from excel in the short strong format.
If anyone could answer, I would really appreciate help.
Thankyou,
THE CODE:
// Get current date and time
DateTime dtx = DateTime.Now;
string Date = dtx.ToShortDateString();
// Calculating the last month's date (substracting days from current date.)
DateTime lastmonth= DateTime.Today.AddDays( -30 );
string Date2 = lastmonth.ToShortDateString();
OleDbCommand objCmdSelect = new OleDbCommand(
"SELECT [Hour],(Format(Date, 'Short Date')) AS text_Date,[U_CSSR] FROM [" + excelSheets[j] + "] WHERE CI=" + id + " AND (Format(Date, 'Short Date'))BETWEEN "+ Date + " AND "+ Date2 + " ", objConn);
I think your WHERE clause is logically incorrect. it should be
... BETWEEN "+ Date2 + " AND "+ Date ...
The earlier date should come first.
BETWEEN a AND b is equal to: x > a and x < b.
I'm trying to insert the current date to the database and i allways get the message(when i press the button on the form to save to my access database), that the data type is incorect in the conditional expression.
the code:
string conString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\Simon\\Desktop\\save.mdb";
OleDbConnection empConnection = new OleDbConnection(conString);
string insertStatement = "INSERT INTO obroki_save "
+ "([ID_uporabnika],[ID_zivila],[skupaj_kalorij]) "
+ "VALUES (#ID_uporabnika,#ID_zivila,#skupaj_kalorij)";
OleDbCommand insertCommand = new OleDbCommand(insertStatement, empConnection);
insertCommand.Parameters.Add("#ID_uporabnika", OleDbType.Char).Value = users.iDTextBox.Text;
insertCommand.Parameters.Add("#ID_zivila", OleDbType.Char).Value = iDTextBox.Text;
insertCommand.Parameters.Add("#skupaj_kalorij", OleDbType.Char).Value = textBox1.Text;
empConnection.Open();
try
{
int count = insertCommand.ExecuteNonQuery();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
empConnection.Close();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
}
I have now cut out the date,( i made access paste the date ), still there is the same problem. Is the first line ok? users.idtextbox.text?
Please help !
try Changing
insertCommand.Parameters.Add("#datum", OleDbType.Char).Value = DateTime.Now;
to
`insertCommand.Parameters.Add("#datum", OleDbType.Char).Value
= DateTime.Now.ToString("dd MMM yyyy HH:mm");`
( or some other acceptable date format)
Assuming that your database actually holds dates, and not strings, for the date column - I think you're trying to insert char values into your date column.
Change
insertCommand.Parameters.Add("#datum", OleDbType.Char).Value = DateTime.Now;
to
insertCommand.Parameters.Add("#datum", OleDbType.Date).Value = DateTime.Now;
I think you are getting issue due to the date format set in your regional settings and the date format accepted by MS Access.
You can use a specific date format as mentioned in following code.
DateTimeFormatInfo ukDTFomat = new CultureInfo("en-GB", false).DateTimeFormat;
DateTime.Now.ToString("yyyy-MM-dd", ukDTFomat);
You can simplify your OleDb usage by adding parameters like this:
OleDbParameter param = new OleDbParameter("#datum", DateTime.Now);
command.Parameters.Add(param);
This uses the override of the OleDbParameter that takes a string (the parameter name) and an object (whatever the value should be for the parameter). This lets OleDb figure out the correct parameter type for you (and saves you a lot of work typing and changing parameter types).
Update: just noticed this is Jet. All bets are off when it comes to Access, so I'm by no means sure the above will work.
You should use the type OleDbType.Date in the parameter. That maps to a DateTime value in .NET and an OLE date (internally represented as double) in the database. That's what Access uses for storing dates.
With any of the other date formats in OleDbType, it will be converted to a string representation that Access doesn't recognise as a date.
If you use OleDbType.Char the DateTime value will be converted to a string using the current culture in .NET, which may or may not be understood by Access depending on what the culture happens to be. In your case it seems that it was not understood.
Are you sure the problem is the date value? I.e., are the other columns really of type Char? For date values, you should use OleDbType.DBDate but you should also use the appropriate type for the other columns.
EDIT
Tested against an Access database with a date column, the following worked (although stripped the time obviously):
cmd.Parameters.Add( "#DateColumn", OleDbType.DBDate ).Value = DateTime.Now;
As well as (which included the time)
cmd.Parameters.Add( "#TestDate", OleDbType.Date ).Value = DateTime.Now;
EDIT As with the date parameters, you should be passing specific types for the other values:
insertCommand.Parameters.Add("#ID_uporabnika", OleDbType.Integer).Value = int.Parse( users.iDTextBox.Text );
insertCommand.Parameters.Add("#ID_zivila", OleDbType.Integer.Value = int.Parse( iDTextBox.Text );
insertCommand.Parameters.Add("#skupaj_kalorij", OleDbType.Integer).Value = int.Parse( textBox1.Text );