You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#实现从SQL Login库LoggedIn表导出数据至独立标签打印

嘿,我给你整理了几个在C#里实现这个需求的靠谱方案,涵盖了从原生底层到ORM框架,甚至UI场景的实现,你可以根据自己的项目情况来选👇

方案1:原生ADO.NET实现(无额外依赖,最基础)

如果你的项目不想引入任何第三方库,用原生ADO.NET是最直接的方式,它能精准控制数据库操作的每一步:

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        // 替换成你的实际数据库连接字符串
        string connectionString = @"Server=YOUR_SERVER;Database=Login;Trusted_Connection=True;";
        
        // using语句自动释放数据库连接资源,避免内存泄漏
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            // 查询LoggedIn表的所有数据
            string query = "SELECT name, clockin FROM LoggedIn";
            
            using (SqlCommand command = new SqlCommand(query, connection))
            using (SqlDataReader reader = command.ExecuteReader())
            {
                // 逐行读取数据,每个记录生成一个"独立标签"(这里用控制台分隔线模拟)
                while (reader.Read())
                {
                    Console.WriteLine("------------------------");
                    Console.WriteLine($"姓名: {reader["name"]}");
                    Console.WriteLine("打卡时间: {0:yyyy-MM-dd HH:mm:ss}", reader["clockin"]);
                    Console.WriteLine("------------------------\n");
                }
            }
        }
    }
}

*注意:*记得把YOUR_SERVER替换成你的实际数据库服务器地址,如果是SQL认证还要加上User ID和Password参数。

方案2:Entity Framework Core(EF Core)实现(ORM框架,代码更简洁)

如果你的项目已经在使用ORM框架,或者想减少重复的数据库操作代码,EF Core是个不错的选择,它能自动把数据库表映射成C#实体类:

首先需要安装NuGet包:Microsoft.EntityFrameworkCore.SqlServer

然后实现实体类和DbContext:

using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;

// 对应LoggedIn表的实体类,属性名和列名尽量一致(EF Core会自动映射)
public class LoggedInRecord
{
    public string Name { get; set; }
    public DateTime ClockIn { get; set; }
}

// 数据库上下文类,负责和数据库交互
public class LoginDbContext : DbContext
{
    // 对应LoggedIn表
    public DbSet<LoggedInRecord> LoggedIn { get; set; }

    // 配置数据库连接
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=YOUR_SERVER;Database=Login;Trusted_Connection=True;");
    }
}

// 使用示例
class Program
{
    static void Main()
    {
        using (var context = new LoginDbContext())
        {
            // 查询所有记录
            var allRecords = context.LoggedIn.ToList();
            
            // 遍历生成独立标签
            foreach (var record in allRecords)
            {
                Console.WriteLine("========================");
                Console.WriteLine($"Name: {record.Name}");
                Console.WriteLine($"Clock-In Time: {record.ClockIn:yyyy-MM-dd HH:mm:ss}");
                Console.WriteLine("========================\n");
            }
        }
    }
}

这个方案的优势是代码更直观,不用写SQL语句(简单查询场景),适合中大型项目的长期维护。

方案3:Dapper轻量ORM实现(兼顾性能和简洁)

如果想要接近原生ADO.NET的性能,又不想写太多重复代码,Dapper是个轻量的选择,它是Stack Overflow官方在用的ORM:

首先安装NuGet包:Dapper

然后实现代码:

using System;
using System.Data.SqlClient;
using System.Linq;
using Dapper;

// 实体类,和表列对应
public class LoggedInRecord
{
    public string Name { get; set; }
    public DateTime ClockIn { get; set; }
}

class Program
{
    static void Main()
    {
        string connectionString = @"Server=YOUR_SERVER;Database=Login;Trusted_Connection=True;";
        
        using (var connection = new SqlConnection(connectionString))
        {
            connection.Open();
            // 用AS关键字把列名映射到实体属性(如果列名和属性名不一致的话)
            string query = "SELECT name AS Name, clockin AS ClockIn FROM LoggedIn";
            // Dapper扩展了SqlConnection,直接把查询结果映射成实体列表
            var records = connection.Query<LoggedInRecord>(query).ToList();
            
            foreach (var record in records)
            {
                Console.WriteLine("------------------------");
                Console.WriteLine($"姓名: {record.Name}");
                Console.WriteLine("打卡时间: {record.ClockIn:yyyy-MM-dd HH:mm:ss}");
                Console.WriteLine("------------------------\n");
            }
        }
    }
}

Dapper的优势是轻量化,性能几乎和原生ADO.NET一样,同时支持实体映射,适合需要灵活写SQL又不想重复造轮子的场景。

额外:UI项目中生成独立Label控件(以WinForms为例)

如果你的需求是在桌面UI里生成可视化的独立标签(比如每个记录一个带边框的Label),可以参考下面的WinForms示例:

using System;
using System.Data.SqlClient;
using System.Windows.Forms;

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    private void MainForm_Load(object sender, EventArgs e)
    {
        string connectionString = @"Server=YOUR_SERVER;Database=Login;Trusted_Connection=True;";
        int yOffset = 20; // 标签的初始Y坐标,用来控制垂直间距
        
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            string query = "SELECT name, clockin FROM LoggedIn";
            
            using (SqlCommand command = new SqlCommand(query, connection))
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    // 创建新的Label控件
                    Label recordLabel = new Label();
                    // 设置标签内容
                    recordLabel.Text = $"姓名: {reader["name"]}\n打卡时间: {reader["clockin"]:yyyy-MM-dd HH:mm:ss}";
                    // 设置标签位置和大小
                    recordLabel.Location = new Point(20, yOffset);
                    recordLabel.Size = new Size(220, 60);
                    // 给标签加边框,区分每个独立标签
                    recordLabel.BorderStyle = BorderStyle.FixedSingle;
                    // 设置字体和对齐方式
                    recordLabel.Font = new System.Drawing.Font("Arial", 10);
                    recordLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
                    
                    // 把标签添加到窗体上
                    this.Controls.Add(recordLabel);
                    // 增加Y坐标,让下一个标签在下方显示
                    yOffset += 70;
                }
            }
        }
    }
}

这个示例会在窗体加载时,自动生成对应每个数据库记录的独立Label控件,每个标签都有自己的位置和样式,完全满足“独立标签”的可视化需求。

内容的提问来源于stack exchange,提问作者Márton Gergő

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:51:48