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
Related
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.
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!
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.
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();
}
string queryString = "SELECT SUM(skupaj_kalorij)as Skupaj_Kalorij "
+ "FROM (obroki_save LEFT JOIN users ON obroki_save.ID_uporabnika=users.ID)"
+ "WHERE (users.ID= " + a.ToString() + ") AND (obroki_save.datum= #datum)";
using (OleDbCommand cmd = new OleDbCommand(queryString,database))
{
DateTime datum = DateTime.Today;
cmd.Parameters.AddWithValue("#datum", datum);
}
loadDataGrid2(queryString);
I tried now with parameters. But i don't really know how to do it correctly. I tried like this, but the parameter datum doesn't get any value(according to c#).
please try this :
database = new OleDbConnection(connectionString);
database.Open();
date = DateTime.Now.ToShortDateString();
string queryString = "SELECT SUM(skupaj_kalorij)as Skupaj_Kalorij "
+ "FROM (obroki_save LEFT JOIN users ON obroki_save.ID_uporabnika=users.ID)"
+ "WHERE users.ID= " + a.ToString()+" AND obroki_save.datum= '" +DateTime.Today.ToShortDateString() + "'";
loadDataGrid2(queryString);
when you use with Date, you must write like this
select * from table where date = '#date'
not like
select * from table where date = #date
While it's usually useful to post the error, I'd hazard a guess and say that you're getting a conversion error with your date.
You should really look at parameterising your queries...
You should read this: http://www.aspnet101.com/2007/03/parameterized-queries-in-asp-net/
And if you can't be bothered reading that, then try changing your 'a' variable to '1; DROP TABLE obroki; --' (but only after you back up your database).
Perhaps you need to write your SQL string in the SQL dialect of the database you're using. In Jet/ACE SQL (what's used by Access), the delimiter for date values is #, so you'd need this:
obroki_save.datum= #" +DateTime.Today.ToShortDateString() + "#"
Of course, some data interface libraries translate these things for you, so that may not be the problem here.