Reputation: 97
I am currently trying to store datetime in the database. The idea is when onclick on the button, the database will store the current datetime in the database. I have tried some methods but they prompt me with this error:
"Incorrect syntax near '26/6/2013 00:00:00'"
This is my codes:
con.Open();
query = "INSERT INTO dbo.url_map (long_url, expiry_date) Values ('" + tbLongURL.Text + "' , '" + DateTime.Today + "')";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@long_url", tbLongURL.Text);
cmd.Parameters.AddWithValue("@expiry_date", DateTime dt = DateTime.ParseExact(DateTime.Today.ToString(), "dd/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture));
cmd.ExecuteNonQuery();
what is wrong with the way i add the date time?
Any help will be greatly appreciated.
Upvotes: 0
Views: 2760
Reputation: 115
You can directly bind the Current Date to 'expiry_date' column in SQL server.
Steps:
Upvotes: 0
Reputation: 76
protected void Button1_Click(object sender, EventArgs e)
{
Insert();
}
public void Insert()
{
try
{
_conn = new SqlConnection(con);
_cmd = new SqlCommand();
_cmd.Connection = _conn;
_conn.Open();
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.CommandText = "insert_date";
_cmd.Parameters.Add("@Date",SqlDbType.DateTime).Value = DateTime.Now;
_cmd.ExecuteNonQuery();
_conn.Close();
}
catch (Exception ex)
{
}
}
Stored Procedure:
create procedure insert_date @Date datetime as insert into DateTable values(@Date)
Result after insertion on table:
1 2013-06-26 14:29:36.987
Upvotes: 0
Reputation: 10030
Corrected query-
query = "INSERT INTO dbo.url_map (long_url, expiry_date) Values ('" + tbLongURL.Text + "', '" + DateTime.Today + "')";
Upvotes: 3
Reputation: 2091
If you use parameters I think your query should be
query = "INSERT INTO dbo.url_map (long_url, expiry_date) Values (@long_url, @expiry_date)";
//this way sqlcommand make sense
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@long_url", tbLongURL.Text);
cmd.Parameters.AddWithValue("@expiry_date", DateTime.Today);
Upvotes: 0