C# 中使用 MySQL 数据库实现本日、本周、本月、本年数据总数统计
获取当前日期和时间:使用 C# 中的
DateTime
类获取当前日期时间信息。构造 MySQL 查询语句:根据不同的时间范围构建 SQL 查询语句,并执行以获取数据总数。
使用 MySQL 数据库连接,并且使用了 MySql.Data
包进行操作:
using System;
using MySql.Data.MySqlClient;
public class Program
{
public static void Main()
{
string connStr = "server=localhost;user=root;database=yourdatabase;port=3306;password=yourpassword;";
MySqlConnection conn = new MySqlConnection(connStr);
conn.Open();
DateTime today = DateTime.Today;
DateTime startOfWeek = today.AddDays(-(int)today.DayOfWeek);
DateTime startOfMonth = new DateTime(today.Year, today.Month, 1);
DateTime startOfYear = new DateTime(today.Year, 1, 1);
int totalCountToday = GetRecordCount(conn, today, today);