How can I retrieve the current time in C# and store it in a database?
Firstly, you need to establish a connection with the database. You can use the SqlConnection class to achieve the connection. Then, you need to create a SqlCommand object to execute the SQL statement. Finally, you can use the DateTime.Now property to retrieve the current time and store it in the database.
Here is an example code:
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
// 创建与数据库的连接
string connectionString = "YourConnectionString";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// 创建 SQL 语句
string sql = "INSERT INTO TableName (ColumnName) VALUES (@CurrentTime)";
// 创建命令对象
using (SqlCommand command = new SqlCommand(sql, connection))
{
// 添加参数
command.Parameters.AddWithValue("@CurrentTime", DateTime.Now);
// 执行 SQL 语句
command.ExecuteNonQuery();
}
}
}
}
Please make sure to replace YourConnectionString with your database connection string, and replace TableName and ColumnName with the table name and column name where you want to store the time.
In this way, the current time will be stored in the database.