当前位置:首页 > 行业动态 > 正文

如何在C中通过两种方法轻松实现数据库数据展示?

C#可通过DataGridView控件绑定DataSet或使用SqlDataReader逐行读取数据,实现数据库内容展示,前者利用可视化组件快速呈现结构化数据,后者通过代码循环遍历记录自定义输出格式,适应不同场景需求。

使用 DataGridView 控件(Windows 窗体应用)

适用场景
适用于桌面应用程序,通过可视化表格控件快速绑定并展示数据。

实现步骤

  1. 配置数据库连接
    使用 SqlConnection 建立与 SQL Server 的连接:

    string connectionString = "Server=YourServer;Database=YourDB;User Id=YourUser;Password=YourPassword;";
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        // 后续操作
    }
  2. 查询数据并填充 DataSet
    通过 SqlDataAdapter 执行 SQL 查询并将结果加载到 DataSet

    string query = "SELECT * FROM Employees";
    SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
    DataSet dataSet = new DataSet();
    adapter.Fill(dataSet, "Employees");
  3. 绑定数据到 DataGridView
    DataSet 中的表绑定到控件:

    dataGridView1.DataSource = dataSet.Tables["Employees"];

注意事项

  • 安全性:建议使用参数化查询防止 SQL 注入。
  • 性能:大数据量时需分页加载(如 OFFSET-FETCH 语句)。

通过 ASP.NET MVC 框架(Web 应用)

适用场景
适用于 Web 应用程序,通过模型绑定和视图模板动态渲染数据。

实现步骤

  1. 定义模型类
    创建与数据库表对应的模型:

    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
    }
  2. 使用 Entity Framework 查询数据
    通过 LINQ 查询数据库并返回结果:

    public class EmployeeController : Controller
    {
        private readonly ApplicationDbContext _context;
        public EmployeeController(ApplicationDbContext context)
        {
            _context = context;
        }
        public ActionResult Index()
        {
            var employees = _context.Employees.ToList();
            return View(employees);
        }
    }
  3. 在视图中渲染数据
    使用 Razor 语法动态生成 HTML 表格:

    <table class="table">
        <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>部门</th>
        </tr>
        @foreach (var employee in Model)
        {
            <tr>
                <td>@employee.Id</td>
                <td>@employee.Name</td>
                <td>@employee.Department</td>
            </tr>
        }
    </table>

优点

  • 松耦合:模型、视图、控制器分离,便于维护。
  • 灵活性:支持前端框架(如 React、Vue)集成。

方法对比

特性 DataGridView(窗体应用) ASP.NET MVC(Web 应用)
开发效率 快速绑定,适合简单场景 需要配置模型和视图,适合复杂项目
扩展性 有限 高(支持 REST API、前端分离)
部署方式 桌面安装 跨平台 Web 部署

安全与最佳实践

  1. 数据库安全
    • 连接字符串加密:存储在 appsettings.jsonWeb.config 中,避免硬编码。
    • 参数化查询:防止 SQL 注入攻击。
  2. 性能优化
    • 使用异步方法(如 async/await)提升并发能力。
    • 启用数据库索引加速查询。

引用说明

  • ADO.NET 数据库操作参考:Microsoft ADO.NET 文档
  • ASP.NET MVC 框架指南:Microsoft MVC 教程
  • SQL Server 最佳实践:SQL Server 文档
0