got ORA-01843 when I try to insert date & time to Oracle - c#

I have A anb B in String format
A = 14/01/2007
B = 22:10:39
I try to insert date and time:
SQL = "insert into MyTbl(Tdate,Ttime) value ('" + Convert.ToDateTime(A) + "','" + Convert.ToDateTime(B) + "')";
i got ORA-01843 error, what I can do ?
thank's in advance

Don't use raw SQL to insert values. Use a parameterized query instead. Parse your strings into .NET DateTime (or DateTimeOffset) and TimeSpan values in the normal way, and then use something like:
string sql = "insert into MyTbl(Tdate,Ttime) values (:date, :time)";
using (OracleCommand cmd = new OracleCommand(sql, connection))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("date", OracleType.DateTime).Value = date;
cmd.Parameters.Add("time", OracleType.IntervalDayToSecond).Value = time;
cmd.ExecuteNonQuery();
}
(Obviously adjust for the types of your actual fields.)

The error is due to the month, try:
TO_DATE(A, 'DD/MM/YYYY')

Remember that Oracle doesn't have a time-only field.
You're trying to insert a time-only field into a datetime. My guess is that the CLR is turning B into 00/00/00 22:10:39, which isn't a valid oracle date. For example:
SQL> select to_date('00/00/00', 'MM/DD/YY') from dual;
select to_date('00/00/00', 'MM/DD/YY') from dual
*
ERROR at line 1:
ORA-01843: not a valid month
Either way, Convert.ToDateTime(B) probably isn't returning the right thing.
Also, this:
"insert into MyTbl(Tdate,Ttime) value ("
should be this:
"insert into MyTbl(Tdate,Ttime) values ("
...but I'm guessing that's just a typo here.

However i tried Jon method, it didnt work for me for date also time. So i found this method for datetime. Maybe that helps someone in next future too.
OracleParameter oPrm;
oPrm = cmd.CreateParameter();
oPrm.ParameterName = ":myDate";
oPrm.OracleDbType = OracleDbType.Date;
oPrm.Value = DateTime.Now; //for date
cmd.Parameters.Add(oPrm);

Related

Passing DateTime.Now into Access database

I am facing a problem on passing the DateTime.Now into Access database:
oleDBCommand.CommandText =
"INSERT INTO tblData "([PIC], [Sampling Date]) "VALUES (#PIC, #SamplingDate)";
oleDBCommand.Parameters.Add(new OleDbParameter("#PIC", combobox1.Text));
oleDBCommand.Parameters.Add(new OleDbParameter("#SamplingDate", DateTime.Now));
I tried a lot of methods from the internet like using oleDBType.Date, DateTime.Now.ToString(), using AddWithValue..... And none of it is working.
Note 1: Database setting [Sampling Date] = Data Type: Date/Time (Format - Long Time), database was
Note 2: Below code was working but I prefer to using .parameters as it look much more organize and easy to manage.
oleDBCommand.CommandText =
"INSERT INTO tblData ([PIC], [Sampling Date]) " VALUES ('" + combobox1.Text + "', '" + DateTime.Now + "')";
You dont need to pass parameter when specifying current date.
Let the ms access sql query handle it, you need to replace #SamplingDate parameter to Date() for example
cmd.CommandText = "INSERT INTO tblData ([PIC], [Sampling Date]) VALUES (#PIC, Date())";
Here is the best explanation Insert today's date
I was struggling with this this week and the accepted answer really did not help me. I found that if I did the assignment of the date+time as an ODBC canonical string (yyyy-mm-dd hh:mi:ss), it worked just fine. So, my C# code looked something like:
InsertCommand.Parameters.Add("#" + column.ColumnName, OleDbType.DBTimeStamp).Value = DateTime.Now.ToString("u");
for the first row and then
InsertCommand.Parameters.Add("#" + column.ColumnName).Value = DateTime.Now.ToString("u")
for the rest.
Try This,
cmd.CommandText = "INSERT INTO tblData ([PIC], [Sampling Date]) VALUES (#PIC, #SamplingDate)";
cmd.Parameters.Add("#PIC",OleDbType.VarChar).Value = combobox1.Text;
cmd.Parameters.Add("#PIC", OleDbType.Date).Value = DateTime.Now;
c# ms-access

insert datetime value gives error "Incorrect syntax near 12"

DateTime myDateTime = Convert.ToDateTime(rd2[0].ToString())
values = myDateTime.ToString("yyyy-MM-dd HH:mm:ss") + " , " + rd2[1].ToString()+ " , " + rd2[2].ToString()+ " , " + rd2[3].ToString()+ " , " + rd2[4].ToString()+ " , " + rd2[5].ToString() ;
i am trying to insert date 2016-04-22 12:58:11 in sql server table of datatype datetime but it gives error "Incorrect syntax near 12"
The string you end up with is similar to this:
2016-04-22 00:00:00,2016-04-22 00:00:00,2016-04-22 00:00:00,2016-04-22 00:00:00
Inserting that into a SQL statement is invalid. You need to wrap each date in single quotes so that you have:
'2016-04-22 00:00:00','2016-04-22 00:00:00','2016-04-22 00:00:00','2016-04-22 00:00:00'
Either way this makes your life difficult and makes your code subject to sql injection and insecure. Consider using parameters like this.
string exampleSQL = "SELECT * from mydatetable where dateOne = #date1 and dateTwo = #date2";
SqlConnection connection = new SqlConnection(/* connection info */);
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("#date1", SqlDbType.DateTime).Value = myDateTime;
command.Parameters.Add("#date2", SqlDbType.DateTime).Value = rd2[1];
This way you dont need to worry about formatting. The system automatically will replace the #date1 and #date2 with the values you specified and it will deal with adding the nescessary structure of the SQL without you having to worry about it.
I strongly suggest using "parametrizing your sql queries"...For example, you can check it out here:
http://www.dreamincode.net/forums/topic/268104-the-right-way-to-query-a-database-parameterizing-your-sql-queries/
Cheers!

C# and saving date field to MS Access database

I am new to Access and saving data to it. I have a date time field which I used in Visual Studio to make the form and chose date time picker. I am not sure where I am going wrong but I know it is the calendar picker causing the issue. I get error syntax error in insert to statement.
Here is the code I have
string When = qaWhendateTimePicker.Value.ToString("HH:mm:ss.fff");
then my save query
SQLString = "INSERT INTO QAAnswers (QuestionID,CallMonitorNumber,When) VALUES('"+QuestionID + "','" + CallMonitorNumber + "','" + When + "');";
This is of course the shorten version. But for the love of me if I take out the when it saves to the database fine
The Access database I have WHEN SET AS DATE / TIME.
Should I have it set to text? I would think no because then I can not pull queries based on date.
Thanks in advance as I been at this for many hours.
UPDATE
Per comment below i have changed the syntax. Here is what i have. If i put the .value or .date it does not work. I am sure it is something I am doing wrong. I get the error failed to convert parameter value from datetimepicker to datetime. Thanks as I am learning a lot doing this in access.
ad.InsertCommand = new OleDbCommand("insert into QAAnswers ([CallMonitorNumber],[When],[ProperGreeting],[AssureHelp],[AccountVerification],[ConfirmCaller],[ProperPoliciesSolutions],[ProperPoliciesAdmin],[AppropriateTools],[TroubleshootingSteps],[ConfirmResolved],[CustomerEducation],[CSATSurvey],[ThanksCallerBrand],[ProfessionalToneAttitude],[CustomerInvolved],[CallPace],[Empathy],[PhoneEtiquette],[DiffuseEscalated],[UnacceptableCallPractice],[Notes],[ScorePotential],[ScoreActual],[FinalScore]) values (#CallMonitorNumber,#When,#ProperGreeting,#AssureHelp,#AccountVerification,#ConfirmCaller,#ProperPoliciesSolutions,#ProperPoliciesAdmin,#AppropriateTools,#TroubleshootingSteps,#ConfirmResolved,#CustomerEducation,#CSATSurvey,#ThanksCallerBrand,#ProfessionalToneAttitude,#CustomerInvolved,#CallPace,#Empathy,#PhoneEtiquette,#DiffuseEscalated,#UnacceptableCallPractice,#Notes,#ScorePotential,#ScoreActual,#FinalScore)", con);
ad.InsertCommand.Parameters.Add("#QuestionID", OleDbType.VarChar).Value = agentIDNumbertextBox.Text.ToString();
ad.InsertCommand.Parameters.Add("#CallMonitorNumber", OleDbType.VarChar).Value = qaCallMonitorNumbertextBox.Text.ToString();
ad.InsertCommand.Parameters.Add("#When", OleDbType.DBDate).Value = qaWhendateTimePicker;
UPDATED ANSWER
I finally figured it out. Not sure if this is the best way but i just ignored the datetimepicker. I wish i could use the datepicker. Instead i just input the date it was added in by using this statement (shorten version ) Notice the [when] and the Date() .
DateTime now = DateTime.Now;
ad.InsertCommand = new OleDbCommand("insert into QAAnswers ([CallMonitorNumber],[When]) values (#CallMonitorNumber,Date())", con);
I hope this helps someone else. I really do not like using access for a DB but that is what i have to work with .
I gave points to marc as i never heard of parametrized query
You should use a parametrized query to do the insert, to avoid SQL injection attacks!
Something like this:
SQLString = "INSERT INTO QAAnswers (QuestionID, CallMonitorNumber, When) VALUES(?, ?, ?);";
and then when you prepare your insert statement, you need to add three parameters (in Access typically defined as p1, p2, p3) and assign values to those.
using (OleDbConnection conn = new OleDbConnection(YourConnectionStringHere))
using (OleDbCommand cmd = new OleDbCommand(SQLString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("p1", OleDbType.VarChar, 50).Value = QuestionID;
cmd.Parameters.Add("p2", OleDbType.VarChar, 50).Value = CallMonitorNumber;
cmd.Parameters.Add("p3", OleDbType.DBDate).Value = When;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
This will also take care of avoiding issues with dates in string format, and issues with single quotes and all those messy things.
You can use this method also:-
write your insert query in a stored procedure(or you can use query directly) then call it in your method
string strcon = ConfigurationManager.ConnectionStrings["YourConnectionStringName"].ConnectionString;
con.ConnectionString = strcon;
con.Open();
SqlCommand cmd = new SqlCommand("[Your_StoredProcedureName]", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.AddWithValue("#value1", value1);
da.SelectCommand.Parameters.AddWithValue("#value2", value2);
da.SelectCommand.Parameters.AddWithValue("#value3", value3);
int result = da.SelectCommand.ExecuteNonQuery();
return result ;
I finally figured it out. Not sure if this is the best way but i just ignored the datetimepicker. I wish i could use the datepicker. Instead i just input the date it was added in by using this statement (shorten version ) Notice the [when] and the Date() .
DateTime now = DateTime.Now;
ad.InsertCommand = new OleDbCommand("insert into QAAnswers ([CallMonitorNumber],[When]) values (#CallMonitorNumber,Date())", con);

How to pass convert expression in parameter using c#?

I had an adhoc insert statement created in c# code using string builder.
var str = new StringBuilder(string.Empty);
str.Append(" INSERT INTO Table_01 ( ID,");
str.Append("Comment,");
str.Append("DateTimeStamp,");
str.Append(" ) VALUES( ");
str.Append("'" + Guid.NewGuid() + "',");
str.Append("'" + CaseComment + "',");
str.Append("CONVERT(DATETIME, '" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "',120)");
I have converted this code to SqlParameter:-
var str = INSERT INTO Table_01(ID,Comment,DateTimeStamp)
VALUES(#ID,#Comment,#DateTimeStamp)
using (var cmd = new SqlCommand(str, con))
{
cmd.Parameters.Add(new SqlParameter("#ID", Guid.NewGuid()));
cmd.Parameters.Add(new SqlParameter("#Comment", CaseComment));
cmd.Parameters.Add(new SqlParameter("#DateTimeStamp", ?????));
cmd.ExecuteNonQuery();
}
Before passing DateTime, I have to make sure that format is equal to "convert(varchar, getdate(), 120) -- 2016-10-23 06:10:55(24h)" as in TSQL.
How will i pass #datetime parameter using TSQL Convert expression?
You can use Convert class. Try something like this,
cmd.Parameters.Add(new SqlParameter("#DateTimeStamp", Convert.ToDateTime(DateTime.Now)));
or
cmdItemSearch.Parameters.Add(new SqlParameter("#EndDate", SqlDbType.DateTime));
cmdItemSearch.Parameters["#EndDate"].Value = DateTime.Now;
Why not using String Format for DateTime ?
Assuming that the database column is actually a DateTime and not varchar you don't need to convert on insert if using a parameter. Databases don't save dates as strings, but as offsets, and the only reason you had to convert it when using your inline SQL was because you had to make sure the DB recognized the string as a DateTime so it could internally convert it back correctly. This is avoided using parameters.
(In other words, just insert DateTime.Now, don't rip it apart into a string)
Honestly, whenever I need to insert the current date/time stamp to a table, I like to use the server date as opposed to the client date. If the app is running on the same box as SQL server then it doesn't matter, but if the app is running on a different box then it's better to have consistent dates from the same timezone. So I would remove the datetime parameter altogether and use the SQL date function GetDate() as follow:
var str = INSERT INTO Table_01(ID,Comment,DateTimeStamp)
VALUES(#ID,#Comment,GetDate())
using (var cmd = new SqlCommand(str, con))
{
cmd.Parameters.Add(new SqlParameter("#ID", Guid.NewGuid()));
cmd.Parameters.Add(new SqlParameter("#Comment", CaseComment));
cmd.ExecuteNonQuery();
}

Data type mismatch in criteria expression | Access, OleDb, C#

I read/update data from MS Access using C#.
My code is:
public static void UpdateLastLogin(int userid, DateTime logintime) ///logintime = DateTime.Now
{
string sql = #"UPDATE [Customers] SET [LastLogin]=?";
OleDbParameter[] prms = new OleDbParameter[] {
new OleDbParameter("#LastLogin",logintime)
};
using (DAL dal = new DAL())
{
dal.UpdateRow(sql, false, prms);
}
}
When it comes to Dates, I having trouble.
This throws a "Data type mismatch in criteria expression." error.
(I removed WHERE clause for keeping it simpler)
Am I suuposed to enclose [LastLogin]=? question mark with single quotes, # signs .. does not help.
Any leads on how to handle DateTime objects with Access and OleDb provider will be greatly appreciated.
Thanks in advance.
There is a known issue with OleDb and dates. Try doing something like:
OleDbParameter p = parameter as OleDbParameter;
if (null == p)
parameter.DbType = DbType.DateTime;
else
p.OleDbType = OleDbType.Date;
Or use explicit format string:
value.ToString("yyyy-MM-dd hh:mm:ss")
I solved this using the following code
OleDbCommand cmd = new OleDbCommand(qry, cnn);
cmd.Parameters.Add("datenow", OleDbType.Date);
cmd.Parameters["datenow"].Value = DateTime.Now;
Firstly, no your SQL statement should be:
"UPDATE Customers SET LastLogin=#LastLogin"
Secondly, the reason you are receiving the date mismatch error will probably be your passing '?' as your date time into the LastLogin field instead of the actual logintime parameter.
maybe try
DateTime.Now.ToShortDateString() + ' ' + DateTime.Now.ToShortTimeString()
instead, pass it as String (and maybe enclose with # then)
Should it not be
"UPDATE Customers SET LastLogin='#LastLogin'"
And #LastLogin should be
logintime.ToString("yyyy-MM-dd hh:mm:ss")
edit
Could you not just inline the whole thing?
"UPDATE Customers SET LastLogin='" + logintime.ToString("yyyy-MM-dd hh:mm:ss") + "'"
Try setting the "DBTYPE" property of the parameter to identify it as a date, datetime or datetime2 as appropriate...
prms[0].DbType = DbType.DateTime;
There are 7 signatures to the new OleDbParameter() call, so you may change the signature instance, or just do explicitly as I sampled above since you only had 1 parameter in this case.

Categories

Resources