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);
Related
string command = "select x,y,z,t,ModifiedDate " +
" from ZZ where PP='" + XX + "' and Type='" + YY + "' order by ModifiedDate";
connection();
SqlCommand command = new SqlCommand(command, con);
command.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
ModifiedDate is a DateTime - in SQL i see "2019-07-23 12:02:35.283"
But when i want to see "dt" in C# i only see "2019-07-23"
how can i see full time with minutes and seconds?
The type of the column in the DataTable is DateTime. ZZ is a table.
You could try setting the row to something like this:
((DateTime)row[0]).ToString("yyyy-MM-dd HH:mm:ss")
Like how you said in the comments just add the formatting to your ToString() when assigning to the variable.
What you had shouldn't even compile, since you can't declare both a string and an SqlCommand object with the same name in the same scope. Run the query like this:
string sql = #"
select x,y,z,t,ModifiedDate
from ZZ
where PP= #XX and Type= #YY
order by ModifiedDate";
DataTable dt = new DataTable();
// .Net connection pooling means you really do want a new connection object most of the time. Don't try to re-use it!
// The "using" blocks make sure your objects are closed and disposed, even if an exception is thrown
using (var con = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(sql, con))
using (var da = new SqlDataAdapter(cmd))
{
//use the actual column types and lengths from your database here
cmd.Parameters.Add("#XX", SqlDbType.NVarChar, 30).Value = XX;
cmd.Parameters.Add("#YY", SqlDbType.NVarChar, 10).Value = YY;
da.Fill(dt);
}
But this still won't fix everything. It's mainly about closing the huge gaping-wide security hole and potential denial-of-service issue in the original code.
The actual issue from the question is in a different place than this code. The time portion of your ModifiedDate column is in the resulting DataTable. Really. I promise. If you don't see it, it's because of a DataView, format string, or other issue at the point where you try to observe or display these results.
There is no Date class in C# - even DateTime.Date() returns another DateTime object with an all zeros time component.
Your problem sounds very much like a Regional Settings issue, or more specifically, CultureInfo in C#. Your default (or "current" as applied by Thread.CurrentThread's CurrentCulture or CurrentUICulture) has its CultureInfo.DateTimeFormat setup to supply date-without-time formatting.
Probably the FullDateTimePattern is set to "yyyy-mm-dd" or something equivalent.
The format in the database for date column is yyyymmdd but my code in aspx.cs passes the parameter value as yyyy-mm-dd. How can I convert yyyy-mm-dd to yyyymmdd in the WHERE clause if my select statement?
aspx.cs code:
adapter.SelectCommand = new SqlCommand("select distinct a.e_id from tenter where (date='" + Convert(DateTime.Value.ToString()) + "')", myConn);
Please don't save your DateTime values as a character.
Type your date column as a datetime or datetime2 and pass your DateTime.Now value directly to your parameterized queries. Otherwise, it will be open for SQL Injection attacks.
Read: Bad habits to kick : choosing the wrong data type
As an example;
using(var myConn = new SqlConnection(conString))
using(var cmd = myConn.CreateCommand())
{
cmd.CommandText = "select distinct a.e_id from tenter where date = #date";
cmd.Parameters.Add(#date, SqlDbType.DateTime2).Value = DateTime.Now;
using(var adapter = new SqlDataAdapter(cmd))
{
// Do your operations.
}
}
Also date might reserved word in future releases of SQL Server. You might need to use it as [date] as well.
It may helps you
You can use this logic and work on your query
declare #a date= '2014/2/3'
select replace(#a,'-','')
use SQL CAST()
SqlCommand cmd=new SqlCommand();
cmd.Connection=con;
cmd.CommandText="select distinct a.e_id from tenter where cast(date as date)=cast(#date as date)";
cmd.Paramenter.AddWithValue("#date",Convert.ToDateTime(DateTime.Value));
adapter.SelectCommand = new SqlCommand ("select distinct a.e_id from tenter where (date='" + DateTime.ParseExact(("2015-03-18"), "yyyy-MM-dd", null).ToString("yyyyMMdd") + "')", myConn);
Thank you very much to all of you.
The best answer for me like this:-
adapter.SelectCommand = new SqlCommand ("select distinct a.e_id from tenter where (date='" + startdate.Value.ToString().Replace("-",string.Empty) + "')", myConn);
Maybe simply : DateTime.Value.ToString().Replace("-",string.empty)
for mysql you can try this :
where date_format(date,'%Y%m%d') = '20150318'
#+jef
I have posted the code I have below
I am trying to get the data from an Access 2002-2003 database
If I take out everything after the WHERE clause and just use "SELECT * FROM [{0}] then it takes all the data from the table with no problems. I have double checked the field names, they are definitely correct. I have more than 1 table with the same field names, so I thought maybe I would need to include the table name before the field name, but with or without the table I still get the same exception. I have tried moving the position of the square brackets, again with no success...
Even if I include only one of the WHERE clauses, the code no longer works, and I can't for the life of me work out why.. I have spent hours looking at numerous posts here and on other sites related to this error, but none of the suggestions have helped me..
The Destination field is a 'memo' field in Access.
The Next Collection fields are date fields, GVars.currentDate is set earlier in the code to be today's date (with the time portion set to 00:00:00).
GVars.thisFY is also set programatically as a string prior to this.
Any tips would be appreciated.
string sql;
OleDbDataAdapter adapter;
sql = string.Format(
"SELECT * FROM [{0}] WHERE {0}.[Destination] = #Destination AND {0}.[Next Collection] BETWEEN #NextCollectionA AND #NextCollectionB"
, GVars.thisFY);
// Create the command object
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
// Add values to the fields
cmd.Parameters.AddWithValue("#Destination", "Henwood");
cmd.Parameters.AddWithValue("#NextCollectionA", GVars.currentDate);
cmd.Parameters.AddWithValue("#NextCollectionB", GVars.currentDate.AddDays(1));
adapter = new OleDbDataAdapter(cmd.CommandText, conn);
System.Diagnostics.Debug.Print(cmd.CommandText);
try
{
adapter.Fill(ds);
GVars.bLblLastUpdate = DateTime.Now.ToString("HH:mm:ss");
}
catch (Exception ex)
{
}
EDIT:
Thanks Vladislav for the answer, corrected code posted below:
string sql;
OleDbDataAdapter adapter;
sql = string.Format(
"SELECT * FROM [{0}] WHERE [{0}].[Destination] = #Destination AND [{0}].[Next Collection] BETWEEN #NextCollectionA AND #NextCollectionB"
, GVars.thisFY);
// Create the command object
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = conn;
// Add values to the fields
cmd.Parameters.Add("#Destination", OleDbType.Char).Value = "Henwood";
cmd.Parameters.Add("#NextCollectionA", OleDbType.DBDate).Value = GVars.currentDate;
cmd.Parameters.Add("#NextCollectionB", OleDbType.DBDate).Value = GVars.currentDate.AddDays(1);
adapter = new OleDbDataAdapter(cmd);
try
{
adapter.Fill(ds);
GVars.bLblLastUpdate = DateTime.Now.ToString("HH:mm:ss");
}
Try to specify types for the parameters you add.
Another thing I notice is that to your adapter you are passing only the CommandText.
You should pass the whole command object.
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
cmd = new OleDbCommand(sqlQuery, conn);
cmd.CommandText = "INSERT INTO tickets (ProblemIncidentDate, ProblemIncidentTime, user, StateTagNumber, ProblemType, ProblemDescription, ProblemStatus) VALUES (#ProblemDate,#ProblemTime,#userIDNumber,#StateTag,#ProblemType,#ProblemDescription,#ProblemStatus)";
cmd.Parameters.Add("#ProblemDate", OleDbType.Date).Value = labelProblemDate.Text.Trim();
cmd.Parameters.Add("#ProblemTime", OleDbType.DBTimeStamp).Value = labelProblemTime.Text.Trim();
cmd.Parameters.Add("#userIDNumber", OleDbType.Integer).Value = Convert.ToInt32(userID.ToString());
cmd.Parameters.Add("#StateTag", OleDbType.VarChar).Value = textBoxStateTagNumber.Text.Trim();
cmd.Parameters.Add("#ProblemType", OleDbType.VarChar).Value = comboBoxProblemType.SelectedItem.ToString();
cmd.Parameters.Add("#ProblemDescription", OleDbType.VarChar).Value = textBoxProblemDescription.Text.Trim();
cmd.Parameters.Add("#ProblemStatus", OleDbType.VarChar).Value = "Open";
cmd.ExecuteNonQuery(); //At this line exception is generating
conn.Close();
My database is a Microsoft Access 2007
Here are the field types
ID AutoNumber
ProblemIncidentDate Date/Time
ProblemIncidentTime Date/Time
user Number
StateTagNumber Text
ProblemType Text
ProblemDescription Memo
ProblemResolution Memo
ProblemStatus Text
I can't figure out why it's crashing
The console message says
A first chance exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Try with the correct datatypes like
cmd.Parameters.Add("#ProblemDate", OleDbType.Date).Value = DateTime.Parse(labelProblemDate.Text.Trim());
cmd.Parameters.Add("#userIDNumber", OleDbType.Integer).Value = Convert.Int32(userID.ToString());
Converted from my comment:
Try putting brackets around [user], it might be keyword. Also, you are passing strings into your Integer and DateTime fields.
I've worked with different OleDb providers and found that some do NOT like named parameters, and instead, just use a "?" as a place-holder for the parameter. Just note that the parameters need to be added in the same sequence as the insert (just like you have), so try changing to..
insert into YourTable( fld1, fld2, fld3 ) values ( ?, ?, ? )
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);