Saving Date and Time - c#

I don't know why the date and time is not saving on my Access Database. I follow some tutorial but it seems I'm having some problems on my code.
DateTime getdate = DateTime.Now;
String time = getdate.ToString("F");
and when I add
OleDbCommand cmdInsert = new OleDbCommand(#"insert into TblInventory (ItemCode,ProductName,Quantity,DateTime)
values ('" + txtItem.Text + "','" + txtProduct.Text + "','" + txtQuantity.Text + "','" + time +"')");
cmdInsert.Connection = con;
cmdInsert.ExecuteNonQuery();
Im stock. please help. thanks guys
The error says that there are problem on the insert into statement

Name of your column is DateTime which is a keyword. You need to change name of column. Also use Parameterized query don't concatenate strings in query.
List of reserved words.

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

Converting String into DateTime AM PM to Insert into SQL Server table

I am trying to convert a textbox text into a DateTime so that I can insert it into the database table into a datetime column.
Here is my code
bookingfromdate text is "08/07/2015 03:00:00 pm"
DateTime bookingfrom = DateTime.ParseExact(bookingfromdate.Text.ToString(),
"dd/MM/yyyy h:mm:ss tt", new CultureInfo("en-US"),DateTimeStyles.None);
The value of bookingfrom is 08/07/2015 15:00:00 and when I insert it in the database, it is throwing an exception:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.The statement has been terminated.
Please help.
and the Insert query is
string sql = "Insert into ITResources_Booking (ResourceID,BookingFrom,BookingTo)
Values (" + Convert.ToInt32(ddControl.SelectedItem.Value.ToString())
+ ",'" + bookingfrom + "','" + bookingto + "')";
Always try to use parameterized queries to avoid SQL Injection
In your query you are converting date time to string again like #Matt Johnson said don't do that.
If you are doing please specify the format of date you are supplying because sql always expect date format in MM/dd/yyyy , yyyy-MM-dd etc formats if the date you supplying is 25/10/2015 it will fail because 25 is not a valid month
So if you are still stick with your query try below
string sql = "Insert into ITResources_Booking (ResourceID,BookingFrom,BookingTo)
Values (" + Convert.ToInt32(ddControl.SelectedItem.Value.ToString())
+ ",'" + bookingfrom.ToString("dd/MM/yyyy HH:mm:ss") + "','" +
bookingto.ToString("dd/MM/yyyy HH:mm:ss") + "')";
OR
string sql = "Insert into ITResources_Booking (ResourceID,BookingFrom,BookingTo)
Values (" + Convert.ToInt32(ddControl.SelectedItem.Value.ToString())
+ ",'" + bookingfrom.ToString("yyyy-MM-dd HH:mm:ss") + "','" +
bookingto.ToString("yyyy-MM-dd HH:mm:ss") + "')";
The error indicates that you're converting the DateTime back to a string when you pass it along to the database. As shown in your insert query, you are passing it inline the SQL query instead of passing it as a parameter.
The simple answer is: don't do that.
Parameterize your inputs. It will help with your dates, and it will prevent SQL Injection attacks.
Your SQL statement should look like this:
string sql = "INSERT INTO Resources_Booking (ResourceID, BookingFrom, BookingTo) VALUES (#ResourceID, #BookingFrom, #BookingTo)";
Then you should add the actual values as parameters when you execute the statement.
var command = new SqlCommand ...etc...
command.CommandText = sql;
command.Parameters.AddWithValue("#ResourceID", theResourceId);
command.Parameters.AddWithValue("#BookingFrom", bookingFrom);
command.Parameters.AddWithValue("#BookingTo", bookingTo);
...
your bookingfrom is DateTime,why you don not use DbParameter?or you can have a try below
string sql = "Insert into ITResources_Booking (ResourceID,BookingFrom,BookingTo) Values (" + Convert.ToInt32(ddControl.SelectedItem.Value.ToString()) + ",'" + bookingfrom.ToString("YYYY-MM-dd HH:mm:ss") + "','" + bookingto + "')";

Syntax error in INSERT INTO statement c#.net Winforms Devexpress?

I get date from DateEdit and try to Store into Access Database. But it show error like this
Syntax error in INSERT INTO statement.
my insert statement is this
OleDbCommand top = new OleDbCommand("INSERT INTO invoice(invoice_number,order_number,customername,status,subtotal,tax,total,date) VALUES (" + inno + "," + odrno + ",'" + name + "','"+ chk1 +"' ,"+ subtottal +","+ tax +","+total+",'"+date+"')", conn);
top.ExecuteNonQuery();
Except Date remaining values store successfully but how can i store date ??
I get date like this DateTime date = dateEdit1.DateTime;
Help me.
DATE is a reserved keyword for Microsoft Access. You shoud use it with square brackets like [DATE]
And you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
OleDbCommand top = new OleDbCommand(#"INSERT INTO invoice(invoice_number,order_number,customername,status,subtotal,tax,total,[date])
VALUES (#invoice_number, #order_number, #customername, #status, #subtotal, #tax, #total, #date)", conn);
top.Parameters.AddWithValue("#invoice_number", inno);
top.Parameters.AddWithValue("#order_number", odrno);
top.Parameters.AddWithValue("#customername", name);
top.Parameters.AddWithValue("#status", chk1);
top.Parameters.AddWithValue("#subtotal", subtotal);
top.Parameters.AddWithValue("#tax", text);
top.Parameters.AddWithValue("#total", total);
top.Parameters.AddWithValue("#date", date);
As a general recommendation, don't use reserved keywords for your identifiers and object names in your database.

"Out-of-range value" error when converting a varchar to datetime

I have this code
datecreation = todaydate.Substring(6, 4) + todaydate.Substring(3, 2) +
todaydate.Substring(0, 2)
string sql = "insert into Usertable ";
sql += "values(" + mVendid + ", '" + usrname + "','" + usrpass + "', cast('" +
datecreation + "'as DATETIME),'" + createdby + "')";
The problem is whenever it is running in server it is giving error. In Local host or in SQL server management it is working fine.
What the heck is it not working whenever it is in the web
The error 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.
Never concatenate string to form SQL queries, always use parameterized query. For your code you can use SqlParameter, with your command. There instead of Converting DateTime to string and then casting it back DateTime in INSERT query , simply add the value of DateTime object in parameter. This will not only save you from Sql Injection but also resolves issues like the one you are having.
Something like:
using(SqlConnection conn = new SqlConnection("Connectionstring"))
using (SqlCommand cmd = new SqlCommand())
{
string sql = "insert into Usertable ";
sql += "values(#mVendid, #usrname, #usrpass, #datecreation, #createdby)";
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#mVendid", mVendid);
cmd.Parameters.AddWithValue("#usrname", username);
cmd.Parameters.AddWithValue("#usrpass", userpass);
cmd.Parameters.AddWithValue("#datecreation", Convert.ToDateTime(datecreation));
cmd.Parameters.AddWithValue("#createdby", createdby);
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
}
if datecreation is coming from a DateTime object then add that directly, otherwise you can parse it to DateTime object and let SQL server handle the rest for you.
The problem is that probably you server has different language settings that your machine.
To make sure that converting is working you Convert function. Full tutorial is here: http://www.sqlusa.com/bestpractices/datetimeconversion/
BTW constructing queries like concatenate string is very dangerous way. Instead of this use SqlParamerts. Moreover advantage using this approach is that .NET will do conversion for you.
First of all user parameters (better, clearer and safer!). Second this error happens due to format issues.
datecreation = todaydate.Substring(6, 4) + todaydate.Substring(3, 2) +
todaydate.Substring(0, 2)
string date = DateTime.Parse(datecreation);
string sql = "insert into Usertable values(#mvendid, #username, #usrpass, #date, #createdby)";
var con = new SqlConnection(""); // your connection string
var cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#mvendid", mVendid);
...
cmd.Parameters.AddWithValue("#date", date);
First of all its really a bad query and quite hacky, you shouldn't be writing query like this
string sql = "insert into Usertable ";
sql += "values(" + mVendid + ", '" + usrname + "','" + usrpass + "', cast('" +
datecreation + "'as DATETIME),'" + createdby + "')";
*Always use Paramaterised Queries *
Error might be there because you are converting some text to datetime. Possible reasons Datetime not well formed
Dateimte doesn't matches to your server datetime
Try to print out the exact value what its creating
cast('" +
datecreation + "'as DATETIME)
Check the time zone of the server. Likely that it is a different time zone to your local machine. You can avoid the issue by using parameters.
string sql = #"
INSERT INTO Usertable
VALUES (#Parameter1, #Parameter2, #Parameter3, #Parameter4, #Parameter5)";
(using SqlCommand command = new SqlCommand(sql, myConnection))
{
command.Parameters.AddWithValue("#Parameter1", mVendid);
command.Parameters.AddWithValue("#Parameter2", usrname);
command.Parameters.AddWithValue("#Parameter3", usrpass);
command.Parameters.AddWithValue("#Parameter4", todaydate);
command.Parameters.AddWithValue("#Parameter5", createdBy);
command.ExecuteNonQuery();
}

SQL statement, OleDbException error INSERT

There is no error in the code, but no information is appearing in the database.
string mysql;
mysql = "INSERT INTO Cars(Make,Model,Price,[Image]) VALUES ('"
+ tbMake.Text + "','" + tbModel.Text + "'," + tbPrice.Text + ",'" + FileUpload1.FileName + "')";
siteDB.InsertCommand = mysql;
DataList1.DataBind();
Cheers.
With an Access database the word IMAGE is a reserved keyword.
If you want to use it you need to encapsulate with square brakets
"INSERT INTO Cars(Make,Model,Price,[Image]) VALUES ......"
This will resolve you immediate problem, but as John Skeet pointed out in its comment you need to use a parametrized query because this solves also the problem of proper formatting of your text values.
What happens to your handy crafted query if a model name (or make) contains a single quote?
Another syntax error is waiting for you (and from my experience it will bite you just when you have finished to code and are ready to work)
Just to complete the answer, feel free to test if in this way it adds the record to your db
mysql = "INSERT INTO Cars(Make,Model,Price,[Image]) VALUES (?,?,?,?)";
OleDbCommand cmd = new OleDbCommand(mysql, con);
cmd.Parameters.AddWithValue("#p1", tbMake.Text);
cmd.Parameters.AddWithValue("#p2", tbModel.Text);
cmd.Parameters.AddWithValue("#p3", Convert.ToDecimal(tbPrice.Text));
cmd.Parameters.AddWithValue("#p4", FileUpload1.FileName);
cmd.ExecuteNonQuery();
I am assuming siteDB is an SQLDataAdapter.
In this case your code should at least be changed to this:
string mysql;
mysql = "INSERT INTO Cars(Make,Model,Price,Image) VALUES ('"
+ tbMake.Text + "','" + tbModel.Text + "'," + tbPrice.Text + ",'" + FileUpload1.FileName + "')";
siteDB.InsertCommand = mysql;
DataList1.DataBind();

Categories

Resources