Updating datetime in access table - c#

I'm trying to insert a datetime value into a datatable and then use the oledbdataadapter's update(datatable) method to load it into my database.. but i keep getting a "Data type mismatch in criteria expression." error. My access Data types in the table are:
ID Number
Nombre_Proyecto Text
Codigo_Ine_Proy Text
Cliente text
Fecha_Creacion Datetime (short date)
according to access short date is mm/dd/yyy, wich fits with my datetime/toshortdatestring method? i think so at least.
Any help would be appreciated. Here's my code:
Insert OledbCommand fot the data adapter:
sql = "PARAMETERS [#Fecha_Creacion] datetime;INSERT Into [Proyectos] ([ID], [Nombre_Proyecto],[Codigo_Ine_Proy],[Cliente],[Fecha_Creacion]) Values (#ID,#Nombre_Proyecto,#Codigo_Ine_Proy,#Cliente,#Fecha_Creacion)";
Comando = new OleDbCommand(sql, conn);
Comando.Parameters.Add("#Nombre_Proyecto", OleDbType.VarWChar, 500, "Nombre_Proyecto");
Comando.Parameters.Add("#Codigo_Ine_Proy", OleDbType.VarWChar, 500, "Codigo_Ine_Proy");
Comando.Parameters.Add("#Cliente", OleDbType.VarWChar, 500, "Cliente");
Comando.Parameters.Add("#Fecha_Creacion", DbType.DateTime);
Comando.Parameters.Add("#ID", OleDbType.Integer, 10000, "ID");
Part where i create the datarow on my datatable:
DataRow newRow = Tabla_Proyectos_BD_General.NewRow();
Max_IDs["Proyectos"] += 1;
newRow["ID"] = Max_IDs["Proyectos"];
newRow["Nombre_Proyecto"] = textBox2.Text;
newRow["Codigo_Ine_Proy"] = textBox1.Text;
newRow["Cliente"] = textBox3.Text;
string x = System.DateTime.Now.ToShortDateString();
newRow["Fecha_Creacion"] = x;
Tabla_Proyectos_BD_General.Rows.Add(newRow);

You should just use
newRow["Fecha_Creacion"] = System.DateTime.Now;
What you see from in the Access is the "formatted date". When interacting thru OleDB you need to use the DateTime and not the formatted string.

string x = System.DateTime.Now.ToShortDateString();
It's a string, not a datetime! hence mismatch.
newRow["Fecha_Creacion"] = System.DateTime.Now;
And your parameterised query should just do it for you.
if you want to show the date you put in there in shortdatestring format (whate ever that is on the pc that does the formatting, get it as a datetime and then format as required.
PS if you want to pass a date as a string to a database, use the formats yyyy-MM-dd or yyyyMMdd. Any other than the universal and unambiguous date formats is just a bug waiting to happen, and never do unless you have to.
Tip when outputting dates, converting them into strings in some format is the last operation, when inputing them, converting to a datetime from the string is the first thing you should do.
Edited after comment
Simplest solution is
Comando.Parameters.Add("#Fecha_Creacion", DbType.DateTime, System.DateTime.Now);

Related

Format a date so it can be written into Oracle ("Not a valid month" error)

Having trouble with finding the proper syntax for this. Here's my field on the ASP side:
<input type="text" id="EI_Open_AuditStartDt" class="datepicker" runat="server"
name="EI_Open_AuditStartDt" value='<%#Eval("Audit_Start_Date") %>'
style="width: 100px" />
Here's part of my code-behind in C#:
HtmlInputText EI_Open_AuditStartDt = (HtmlInputText)DataGrid_Open.Rows[e.RowIndex].FindControl("EI_Open_AuditStartDt");
TextBox EI_Open_TransCIT = (TextBox)DataGrid_Open.Rows[e.RowIndex].FindControl("EI_Open_TransCIT");
string StartDt = String.Format("{0:dd-mmm-yyyy}", EI_Open_AuditStartDt.Value);
string TransCIT = EI_Open_TransCIT.Text;
DataGrid_RootCauses.EditIndex = -1;
OracleConnection conn = GetConnection();
try
{
using (OracleCommand cmd = new OracleCommand("CST_AMR_WRITE_OPENSTATUS", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
using (OracleDataAdapter da = new OracleDataAdapter(cmd))
{
cmd.Parameters.AddWithValue("v_StartDt", OracleType.DateTime).Value = StartDt;
cmd.Parameters.AddWithValue("v_TransCIT", OracleType.VarChar).Value = TransCIT;
The problem is, when it gets to string StartDt, it still sees the value as, say, "03/24/2017" instead of "24-MAR-17", so I'm getting the "Not a valid month" error.
Can anyone see what I'm doing wrong?
Verify the format of the data stored in the Oracle DB.
Attempt to insert the data as a raw string, in that format and see if it succeeds.
That takes your calling code out of the possible variables affecting your problem.
If that still doesn't work, you have to look at the stored procedure and figure out if it's converting formats without your knowledge.
If you don't have the ability to see the stored procedure, you are going to have to try a bunch of different formats in your calling code until you find the right one.
I would suggest inserting the value using ISO 8601 format - i.e. yyyy-MM-dd
var StartDt = Date.ParseExact(EI_Open_AuditStartDt.Value,"dd-MM-yyyy", CultureInfo.InvariantCulture););
//.....
cmd.Parameters.AddWithValue("v_StartDt", OracleType.DateTime).Value = StartDt.ToString("yyyy-MM-dd");
Although, there is a good chance that you could do away with the date formatting in the param add, and simply hand it the StartDt object.
cmd.Parameters.AddWithValue("v_StartDt", OracleType.DateTime).Value = StartDt;
I came up with this, and it worked:
DateTime dt1 = Convert.ToDateTime(EI_Open_SubmissionDt.Value);
var SubDt = String.Format("{0:dd-MMM-yyyy}", dt1);
Would anyone with more C#/Oracle experience than I (which is pretty much everyone) care to poke holes in it? Is this a legitimate answer, or are there potential issues with it?
format in C# var StartDt = Date.FormatExact(EI_Open_AuditStartDt.Value, "DD/MM/YY"); or if to be exact to format of your database nls_date_format.
Or you can use c# DateTime and do following , note that function returns bool, you can check it in if operator and then assign myDTvar to command parameter.
DateTime myDTvar;
DateTime.TryParseExact(StartDt, "dd-mmm-yyyy", null,
DateTimeStyles.None, out myDTvar)

How to execute a delete query that includes a varchar and datetime field in the WHERE clause

Hello i try to delete from a Table where i need to access a varchar note field and an datetimefield.
Here is the Code:
DateTime test = (DateTime)powerPlant.timestamp;
string DateUS = test.ToString("s");
string deletePowerPlant =
String.Format(
"DELETE FROM [dbo].[tblSPpowerPlants] WHERE [timestamp] = CONVERT(datetime,"+ DateUS +",111) AND [note] = {0};",
note);
SqlCommand sqlDelete = new SqlCommand(deleteComponents, sqlConnection);
sqlDeletePowerPlant.CommandType = CommandType.Text;
sqlDeletePowerPlant.CommandText = deleteComponents;
sqlDeletePowerPlant.ExecuteNonQuery();
And yes normally i would use sql parameters but i want to know how it would work without parameters just to test it out becouse somehow it must be possible. I tried to google it and with some other forum and some blogs but had no luck.
Thx for your help and sorry for my english.
EDIT
The Field timestamp is a Datetime in the table.
The note is a nvarchar in the Table. And i just want to use it once so i can say i know how to do it without parameters. I know its bad....
You'll want to make sure there is no dependency on server operating system locale. So if you use a certain format (111 in your case) in the SQL query, you should use the .NET equivalent to convert your date to a string:
string DateUS = test.ToString("yyyy/MM/dd");
For details about the formats that the CONVERT function supports, see here:
https://msdn.microsoft.com/de-de/library/ms187928(v=sql.120).aspx
As you stated yourself in the question, using a (strongly typed) SqlParameter is the preferred way to go. Failing to so so may result in sql injection vulnerabilities.
Given that note is a text column, single quotes and escaping will be required:
String.Format(
"DELETE FROM [dbo].[tblSPpowerPlants] WHERE [timestamp]=CONVERT(datetime,'{0}',111) AND [note]='{1}'",
DateUS
note.Replace("'","''").Replace(#"\",#"\\")
);
If you store time-of-day too, the comparison with = will not affect records with nonzero time component.
Put some string qualifiers in there
DateTime test = (DateTime)powerPlant.timestamp;
string DateUS = test.ToString("s");
string deletePowerPlant = String.Format("DELETE FROM [dbo].[tblSPpowerPlants] WHERE [timestamp] = CONVERT(datetime,'"+ DateUS +"',111) AND [note] = '{0}';", note);
SqlCommand sqlDelete = new SqlCommand(deleteComponents, sqlConnection);
sqlDeletePowerPlant.CommandType = CommandType.Text;
sqlDeletePowerPlant.CommandText = deleteComponents;
sqlDeletePowerPlant.ExecuteNonQuery();
But really. Use parameterized queries

Updating DateTime in access through C#. Data mismatch

I have a date and time loaded into a textbox for editing, but I need to store it as a datetime in my access database not a string and cannot remember or find the syntax to parse it in my SQL parameters... here is my code anyway...
string strSql = "UPDATE OCR SET OCR = #OCR, [OCR Title] = #OCRTitle, DeadlineDate = #DeadlineDate;";
using (OleDbConnection newConn = new OleDbConnection(strProvider))
{
using (OleDbCommand dbCmd = new OleDbCommand(strSql, newConn))
{
dbCmd.CommandType = CommandType.Text;
dbCmd.Parameters.AddWithValue("#OCRTitle", textBox6.Text);
dbCmd.Parameters.AddWithValue("#OCR", textBox5.Text);
dbCmd.Parameters.AddWithValue("#DeadlineDate", textBox7.Text);
newConn.Open();
dbCmd.ExecuteNonQuery();
}
}
You're specifying a string as the deadline date value. You should specify a DateTime instead.
You can use DateTime.Parse (or DateTime.ParseExact, or DateTime.TryParseExact) to parse the text representation if you really have to - but it would be better to use a date-based control to start with, rather than having a text representation at all.
(It's not clear what sort of application this is - WinForms, ASP.NET etc - but most GUIs have some sort of date picker these days.)
EDIT: Additionally, you need to change the order in which you add the parameters to the command such that it matches the order in which the parameters are used in the SQL statement. These are effectively positional parameters - the names are ignored. It would probably be clearer to use ? than named parameters in the SQL.

How to get SQL Server datetime value as it is in 24 hours in C#

I am developing an app in VS2010 c# to fetch a single row data from SQLServer and insert it to MySQL.
I have a table with column name Date_Time containing date and time in 24 hrs. format as shown in below image.
Fetching code is as below.
SqlCommand cmd = new SqlCommand("SELECT TOP (1) s_name, s_city, s_address, s_added_date, s_added_by FROM tblAQI ORDER BY s_added_date DESC", SSCon);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
s_name = (dr["s_name"].ToString());
s_city = (dr["s_city"].ToString());
s_address = (dr["s_address"].ToString());
s_added_date = (dr["s_added_date"].ToString());
s_added_by = (dr["s_added_by"].ToString());
}
when I print the value of s_added_date it gives me
My question is why it showing like this and how can I get this time in 24 hrs. format.
Please help to resolve it.
Thanks in advance.
I have a table with column name Date_Time containing date and time in 24 hrs. format
No, you have a table with a column type of DateTime. The values don't inherently have any format - they just happen to be displayed one way in your SQL results viewer, which isn't the same way as .NET formats them by default.
It's very important to understand that the data here is just the date and time - not the format.
To format it in a particular way, cast it to DateTime and then use a ToString overload which allows you to specify the format:
DateTime addedDate = (DateTime) sr["s_added_date"];
string addedDateText = addedDate.ToString("dd-MMM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
See the MSDN articles on standard date/time formatting and custom date/time formatting for more information.
However, if the purpose is really just to insert it into MySQL, you shouldn't convert it into a string at all. Just pass the parameter value straight into the appropriate MySQL command as a parameter. Adding string conversions just adds confusion. Wherever possible, keep data in its "natural" type - which in this case is DateTime.
Make following line:
s_added_date = (dr["s_added_date"].ToString());
To
s_added_date = (dr["s_added_date"].ToString("dd/MM/yyyy HH:mm:ss"));
Your code will be:
SqlCommand cmd = new SqlCommand("SELECT TOP (1) s_name, s_city, s_address, s_added_date, s_added_by FROM tblAQI ORDER BY s_added_date DESC", SSCon);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
s_name = (dr["s_name"].ToString());
s_city = (dr["s_city"].ToString());
s_address = (dr["s_address"].ToString());
s_added_date = (dr["s_added_date"].ToString("dd/MM/yyyy hh:mm:ss"));
s_added_by = (dr["s_added_by"].ToString());
}
If ypu want it as 11-Nov-2013 10:23:25 format:
s_added_date = (dr["s_added_date"].ToString("dd-MMM-yyyy hh:mm:ss"));
Try this
SqlCommand cmd = new SqlCommand("SELECT TOP (1) s_name, s_city, s_address, DATE_FORMAT(s_added_date,'%T'), s_added_by FROM tblAQI ORDER BY s_added_date DESC", SSCon);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
s_name = (dr["s_name"].ToString());
s_city = (dr["s_city"].ToString());
s_address = (dr["s_address"].ToString());
s_added_date = (dr["s_added_date"].ToString());
s_added_by = (dr["s_added_by"].ToString());
}

Date conversion from C# to MySql Format

How to convert C# datetime to MySql Datetime format. I am getting value from text box like 7/27/2011 this format. But i want to convert in this format 2011-7-27. So here i am stuking. Please help me. My objective is to filter the record between two dates and show in a listview control in asp.net.
Here is my code:
DateTime dt1 = Convert.ToDateTime(txtToDate.Text);
DateTime dt2 = Convert.ToDateTime(txtFromDate.Text);
lvAlert.DataSource = facade.GetAlertsByDate(dt1, dt2);
lvAlert.DataBind();
I haven't used MySQL with .NET, but Oracle has similar date conversion issues with .NET. The only way to stay snae with this has been to use parameters for date values, both for input as welll as for WHERE clause comparisons. A parameter created with a MySQL date parameter type, and just giving it a .NET datetime value, should work without needing you to do conversions.
EDITED TO ADD SAMPLE CODE
This code sample shows the basic technique of using parameters for DateTime values, instead of coding conversions to text values and embedding those text values directly in the SQL command text.
public DataTable GetAlertsByDate(DateTime start, DateTime end)
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(
"SELECT * FROM Alerts WHERE EventTime BETWEEN #start AND #end", conn);
DataTable table = new DataTable();
try
{
SqlParameter param;
param = new SqlParameter("#start", SqlDbType.DateTime);
param.Value = start;
cmd.Parameters.Add(param);
param = new SqlParameter("#end", SqlDbType.DateTime);
param.Value = end;
cmd.Parameters.Add(param);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(table);
}
finally
{
cmd.Dispose();
conn.Close();
conn.Dispose();
}
return table;
}
This is SQL Server code, but the technique should be the same for most databases. For Oracle, for example, the only changes would be to use Oracle data access objects, and use ":" in place of "#" in parameter names. The technique for MySQL should also be very similar.
For many databases, shortcuts may exist for creating parameters, such as:
cmd.Parameters.AddWithValue("#start", start);
This works when you know the value is not null, and the correct parameter type can be derived from the C# type of the value. "AddWithValue" is specific to SQL Server; "Add" works also but is obsolete in SQL Server.
Hope this helps.
You can assign format to data time, DateTime.ParseExact() or DateTime.ToString(format), :
the format for 2011-7-27 is yyyy-m-dd
Assuming you are doing this in the database I think you should use date_format to get in the required format
Something like date_format(dateval,'%Y-%c-%d') (Not tested)
I use:
string fieldate = dt1.ToString("yyyy-MM-dd");

Categories