First, convert it to a TimeSpan object:
string timeFromYourTextBox = "14:37";
TimeSpan time = TimeSpan.Parse(timeFromYourTextBox);
Then, pass it through to SQL via a parameter in the normal way:
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand com = new SqlCommand("INSERT INTO myTable (myTimeColumn) VALUES (@THETIME)", con))
{
com.Parameters.AddWithValue("@THETIME", time);
com.ExecuteNonQuery();
}
}
I defined a field in which represent entrance time of people to company.I want save this time in a short style "hh:mm:ss" to my sql Database.so I choosed Time(7) Data type in sql and TimeStamp Type in C# class.now I need to know How Convert time from TimeStamp to Time(7) in sql and vice versa.
Timespan and Time are interchangeable: just pass a TimeSpan as a Parameter in your INSERT or UPDATE command, and SQL will understand it as a Time.
Similarly, just read the Time back from SQL via a SELECT, and cast it to a TimeSpan - the system will take care of it. So, if Id is INT, and TimeStamp is TIME(7):
using (SqlConnection con = new SqlConnection(@"Data Source=GRIFFPC\SQLEXPRESS;Initial Catalog=Testing;Integrated Security=True"))
{
con.Open();
for (int i = 0; i < 5; i++)
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO myTable2 (Id, TimeStamp) VALUES (@ID, @TS)", con))
{
cmd.Parameters.AddWithValue("@ID", i);
cmd.Parameters.AddWithValue("@TS", new TimeSpan(1, i, 30));
cmd.ExecuteNonQuery();
}
}
}
And:
using (SqlConnection con = new SqlConnection(@"Data Source=GRIFFPC\SQLEXPRESS;Initial Catalog=Testing;Integrated Security=True"))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Id, TimeStamp FROM myTable2", con))
{
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
int id = (int)read["Id"];
TimeSpan ts = (TimeSpan)read["TimeStamp"];
Console.WriteLine("{0}:{1}", id, ts);
}
}
}
}