How to save date and time in database
Haii...
Im trying to save date and time in database. Right now im trying declared time and date, but have problem in assigning it to a variable, where afterwords im try to use it to insert in the database. This is the code that i use:
Code:
Dim dt As DateTime = DateTime.Now
lblTimeNow.Text = dt.ToLocalTime
Dim masa As String
masa = dt.ToLocalTime.ToString()
Dim DataSource As New SqlConnection("Data Source=ANNAS\SQLEXPRESS; Initial Catalog=DBRMS;Integrated Security=True")
Dim command As New SqlCommand("INSERT INTO Customers(Time) VALUES (masa)", DataSource)
DataSource.Open()
command.ExecuteNonQuery()
DataSource.Close()
After been compiled i get this error message
The name "masa" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
Can,anyone help me with this, thank u
Re: How to save date and time in database
Like this:
Code:
Dim command As New SqlCommand("INSERT INTO Customers(Time) VALUES ('" & masa & "')", DataSource)
Since masa is a var it needs to be outside the string (concat). Since you are storeing a dateTime in SQL Server the var needs to be enclosed in single qoutes.
edit
I would also place Time in Square Brackets ([Time])
Re: How to save date and time in database
vb Code:
Dim dt As DateTime = DateTime.Now
lblTimeNow.Text = dt.ToLocalTime
Dim DataSource As New SqlConnection("Data Source=ANNAS\SQLEXPRESS; Initial Catalog=DBRMS;Integrated Security=True")
Dim command As New SqlCommand("INSERT INTO Customers(Time) VALUES (@masa)", DataSource)
'2003 syntax
'command.Parameters.Add("@masa", dt.ToLocalTime)
'2005 syntax
command.Parameters.AddWithValue("@masa", dt.ToLocalTime)
DataSource.Open()
command.ExecuteNonQuery()
DataSource.Close()
How to save date and time in database
i already try it, and it works perfetly.
tHanks a lot to GaryMazzone and wild_bill