开源 C# 快速开发(十六)数据库--sqlserver增删改查

文章的目的为了记录使用C# 开发学习的经历。开发流程和要点有些记忆模糊,赶紧记录,防止忘记。

相关链接:

开源 C# 快速开发(一)基础知识

开源 C# 快速开发(二)基础控件

开源 C# 快速开发(三)复杂控件

开源 C# 快速开发(四)自定义控件--波形图

开源 C# 快速开发(五)自定义控件--仪表盘

开源 C# 快速开发(六)自定义控件--圆环

开源 C# 快速开发(七)通讯--串口

开源 C# 快速开发(八)通讯--Tcp服务器端

开源 C# 快速开发(九)通讯--Tcp客户端

开源 C# 快速开发(十)通讯--http客户端

开源 C# 快速开发(十一)线程

开源 C# 快速开发(十二)进程监控

开源 C# 快速开发(十三)进程--管道通讯

开源 C# 快速开发(十四)进程--内存映射

开源 C# 快速开发(十五)进程--windows消息

开源 C# 快速开发(十六)数据库--sqlserver增删改查

推荐链接:

开源 C# .net mvc 开发(一)WEB搭建_c#部署web程序-CSDN博客

开源 C# .net mvc 开发(二)网站快速搭建_c#网站开发-CSDN博客

开源 C# .net mvc 开发(三)WEB内外网访问-CSDN博客

开源 C# .net mvc 开发(四)工程结构、页面提交以及显示-CSDN博客

开源 C# .net mvc 开发(五)常用代码快速开发_c# mvc开发-CSDN博客

开源 C# .net mvc 开发(六)发送邮件、定时以及CMD编程-CSDN博客

开源 C# .net mvc 开发(七)动态图片、动态表格和json数据生成-CSDN博客

开源 C# .net mvc 开发(八)IIS Express轻量化Web服务器的配置和使用-CSDN博客

开源 C# .net mvc 开发(九)websocket--服务器与客户端的实时通信-CSDN博客

本章节主要内容是:C#对sqlserver数据库,进行增删改查的例子。

目录:

1.源码分析

2.所有源码

3.效果演示

一、源码分析

  1. CreateUserTableIfNotExists() 函数

功能:检查并创建用户表

具体实现:

使用 sysobjects 系统表检查 'user' 表是否存在

如果不存在则创建包含以下字段的表:

Id:自增主键(IDENTITY(1,1))

Username:唯一用户名,NVARCHAR(50),非空

Password:密码,NVARCHAR(100),非空

Email:邮箱,NVARCHAR(100),可为空

CreatedDate:创建时间,DATETIME,默认当前时间

LastLogin:最后登录时间,DATETIME,可为空

IsActive:激活状态,BIT,默认激活

执行成功后输出创建成功消息

复制代码
public void CreateUserTableIfNotExists()
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    string createTableSql = @"
                IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='user' AND xtype='U')
                BEGIN
                    CREATE TABLE [user] (
                        Id INT IDENTITY(1,1) PRIMARY KEY,
                        Username NVARCHAR(50) NOT NULL UNIQUE,
                        Password NVARCHAR(100) NOT NULL,
                        Email NVARCHAR(100),
                        CreatedDate DATETIME NOT NULL DEFAULT GETDATE(),
                        LastLogin DATETIME NULL,
                        IsActive BIT NOT NULL DEFAULT 1
                    )
                    PRINT 'User表创建成功!'
                END";

                    using (SqlCommand command = new SqlCommand(createTableSql, connection))
                    {
                        command.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"创建表失败:{ex.Message}");
            }
        }
  1. AddUser(string username, string password, string email) 函数

功能:向用户表插入新用户记录

参数处理:

对邮箱参数进行空值检查,如果为空则插入 DBNull.Value

异常处理:

捕获 SQL 异常 2627(唯一约束冲突),抛出"用户名已存在"异常

捕获其他异常并封装为添加用户失败消息

复制代码
public bool AddUser(string username, string password, string email)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    string insertSql = @"
                INSERT INTO [user] (Username, Password, Email) 
                VALUES (@Username, @Password, @Email)";

                    using (SqlCommand command = new SqlCommand(insertSql, connection))
                    {
                        command.Parameters.AddWithValue("@Username", username);
                        command.Parameters.AddWithValue("@Password", password);
                        command.Parameters.AddWithValue("@Email", string.IsNullOrEmpty(email) ? DBNull.Value : (object)email);
                      

                        int rowsAffected = command.ExecuteNonQuery();
                        return rowsAffected > 0;
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                if (sqlEx.Number == 2627) // 唯一约束冲突
                {
                    throw new Exception("用户名已存在!");
                }
                throw new Exception($"添加用户失败:{sqlEx.Message}");
            }
            catch (Exception ex)
            {
                throw new Exception($"添加用户失败:{ex.Message}");
            }
        }
  1. DeleteUser(int userId) 函数

功能:根据用户ID删除用户记录

实现方式:

构建 DELETE 语句,使用参数化查询防止SQL注入

通过 ExecuteNonQuery() 执行删除操作

返回布尔值表示删除是否成功(影响行数 > 0)

复制代码
public bool DeleteUser(int userId)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    string deleteSql = "DELETE FROM [user] WHERE Id = @Id";

                    using (SqlCommand command = new SqlCommand(deleteSql, connection))
                    {
                        command.Parameters.AddWithValue("@Id", userId);

                        int rowsAffected = command.ExecuteNonQuery();
                        return rowsAffected > 0;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"删除用户失败:{ex.Message}");
            }
        }
  1. UpdateUser(int userId, string username, string password, string email, bool isActive) 函数

功能:更新指定用户的完整信息

更新字段:用户名、密码、邮箱、激活状态

参数处理:

邮箱字段的空值处理与 AddUser 相同

所有字段均参与更新,无选择性更新逻辑

异常处理:包含唯一约束冲突的特殊处理

复制代码
public bool UpdateUser(int userId, string username, string password, string email, bool isActive)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    string updateSql = @"
                UPDATE [user] 
                SET Username = @Username, 
                    Password = @Password, 
                    Email = @Email, 
                    IsActive = @IsActive
                WHERE Id = @Id";

                    using (SqlCommand command = new SqlCommand(updateSql, connection))
                    {
                        command.Parameters.AddWithValue("@Id", userId);
                        command.Parameters.AddWithValue("@Username", username);
                        command.Parameters.AddWithValue("@Password", password);
                        command.Parameters.AddWithValue("@Email", string.IsNullOrEmpty(email) ? DBNull.Value : (object)email);                
                        command.Parameters.AddWithValue("@IsActive", isActive);

                        int rowsAffected = command.ExecuteNonQuery();
                        return rowsAffected > 0;
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                if (sqlEx.Number == 2627)
                {
                    throw new Exception("用户名已存在!");
                }
                throw new Exception($"更新用户失败:{sqlEx.Message}");
            }
            catch (Exception ex)
            {
                throw new Exception($"更新用户失败:{ex.Message}");
            }
        }
  1. GetAllUsers() 函数

功能:获取所有用户记录

返回类型:DataTable

查询逻辑:

按 Id 排序返回所有用户

使用 SqlDataAdapter 填充 DataTable

包含完整的用户字段选择

复制代码
public DataTable GetAllUsers()
        {
            DataTable dataTable = new DataTable();

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    string selectSql = @"
                SELECT 
                    Id,
                    Username,
                    Password,
                    Email,
                    CreatedDate,
                    LastLogin,
                    IsActive
                FROM [user] 
                ORDER BY Id";

                    using (SqlCommand command = new SqlCommand(selectSql, connection))
                    using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                    {
                        adapter.Fill(dataTable);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"查询用户失败:{ex.Message}");
            }

            return dataTable;
        }
  1. GetUserById(int userId) 函数

功能:根据用户ID精确查询用户

查询方式:使用参数化查询,精确匹配 Id 字段

复制代码
public DataTable GetUserById(int userId)
        {
            DataTable dataTable = new DataTable();

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    string selectSql = "SELECT * FROM [user] WHERE Id = @Id";

                    using (SqlCommand command = new SqlCommand(selectSql, connection))
                    {
                        command.Parameters.AddWithValue("@Id", userId);

                        using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                        {
                            adapter.Fill(dataTable);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"查询用户失败:{ex.Message}");
            }

            return dataTable;
        }
  1. GetUserByUsername(string username) 函数

功能:根据用户名模糊查询用户

查询方式:使用 LIKE 操作符和 % 通配符进行模糊匹配

参数处理:在参数值前后添加 % 通配符

复制代码
public DataTable GetUserByUsername(string username)
        {
            DataTable dataTable = new DataTable();

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    string selectSql = "SELECT * FROM [user] WHERE Username LIKE @Username";

                    using (SqlCommand command = new SqlCommand(selectSql, connection))
                    {
                        command.Parameters.AddWithValue("@Username", $"%{username}%");

                        using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                        {
                            adapter.Fill(dataTable);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"查询用户失败:{ex.Message}");
            }

            return dataTable;
        }

Form1 类详细功能分析

  1. 构造函数

初始化流程:

初始化界面组件

创建 UserService 实例

调用 InitializeDatabase()(当前被注释)

调用 LoadUserData() 加载初始数据

复制代码
        public Form1()
        {
            InitializeComponent();
            InitializeDatabase();
            LoadUserData();
        }
  1. InitializeDatabase() 函数

功能:初始化数据库表结构

当前状态:表创建功能被注释,仅保留异常处理框架

复制代码
        private void InitializeDatabase()
        {
            try
            {
                //userService.CreateUserTableIfNotExists();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"数据库初始化失败:{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
  1. btnAdd_Click() 事件处理函数

功能:处理添加用户按钮点击

验证逻辑:

检查用户名和密码是否为空或空白

显示警告消息如果验证失败

执行流程:

调用 userService.AddUser() 添加用户

成功后清空输入框并刷新数据

复制代码
private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtUsername.Text) || string.IsNullOrWhiteSpace(txtPassword.Text))
                {
                    MessageBox.Show("用户名和密码不能为空!", "警告",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                bool success = userService.AddUser(
                    txtUsername.Text.Trim(),
                    txtPassword.Text,
                    txtEmail.Text.Trim()
                );

                if (success)
                {
                    MessageBox.Show("用户添加成功!", "成功",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearInputs();
                    LoadUserData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
  1. btnUpdate_Click() 事件处理函数

功能:处理更新用户按钮点击

前置检查:

验证是否在 DataGridView 中选择了用户

获取当前选中行的用户ID

执行流程:

调用 userService.UpdateUser() 更新用户信息

成功后清空输入并刷新显示

复制代码
private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null)
            {
                MessageBox.Show("请先选择要修改的用户!", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            try
            {
                int userId = Convert.ToInt32(dataGridView1.CurrentRow.Cells["Id"].Value);

                bool success = userService.UpdateUser(
                    userId,
                    txtUsername.Text.Trim(),
                    txtPassword.Text,
                    txtEmail.Text.Trim(),

                    chkIsActive.Checked
                );

                if (success)
                {
                    MessageBox.Show("用户更新成功!", "成功",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearInputs();
                    LoadUserData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
  1. btnDelete_Click() 事件处理函数

功能:处理删除用户按钮点击

确认机制:

显示确认对话框要求用户确认删除操作

仅在用户选择"是"时执行删除

执行流程:

获取选中行的用户ID

调用 userService.DeleteUser() 删除用户

成功后刷新数据网格

复制代码
private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null)
            {
                MessageBox.Show("请先选择要删除的用户!", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var result = MessageBox.Show("确定要删除这个用户吗?", "确认删除",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                try
                {
                    int userId = Convert.ToInt32(dataGridView1.CurrentRow.Cells["Id"].Value);
                    bool success = userService.DeleteUser(userId);

                    if (success)
                    {
                        MessageBox.Show("用户删除成功!", "成功",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadUserData();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
  1. btnSearch_Click() 事件处理函数

功能:处理搜索用户按钮点击

搜索逻辑:

如果搜索框为空,显示所有用户 (GetAllUsers())

如果搜索框有内容,按用户名模糊搜索 (GetUserByUsername())

结果显示:直接将查询结果绑定到 DataGridView

复制代码
private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable users;
                if (string.IsNullOrWhiteSpace(txtSearch.Text))
                {
                    users = userService.GetAllUsers();
                }
                else
                {
                    users = userService.GetUserByUsername(txtSearch.Text.Trim());
                }
                dataGridView1.DataSource = users;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
  1. btnRefresh_Click() 事件处理函数

功能:处理刷新按钮点击,重新加载所有用户数据

复制代码
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadUserData();
        }
  1. LoadUserData() 函数

功能:加载并显示所有用户数据

界面配置:

将用户数据绑定到 DataGridView

设置列标题的中文显示文本

配置各列的显示名称

复制代码
private void LoadUserData()
        {
            try
            {
                DataTable users = userService.GetAllUsers();
                dataGridView1.DataSource = users;

                // 设置列标题
                if (dataGridView1.Columns.Count > 0)
                {
                    dataGridView1.Columns["Id"].HeaderText = "ID";
                    dataGridView1.Columns["Username"].HeaderText = "用户名";
                    dataGridView1.Columns["Password"].HeaderText = "密码";
                    dataGridView1.Columns["Email"].HeaderText = "邮箱";
                    dataGridView1.Columns["CreatedDate"].HeaderText = "创建时间";
                    dataGridView1.Columns["LastLogin"].HeaderText = "最后登录";
                    dataGridView1.Columns["IsActive"].HeaderText = "是否激活";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败:{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
  1. dataGridView1_SelectionChanged() 事件处理函数

功能:处理数据网格选择变化事件

数据绑定:

当用户选择不同行时,自动将选中用户的数据填充到编辑表单

填充字段包括:用户名、密码、邮箱、激活状态

处理空值情况,使用空字符串替代 null 值

复制代码
        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow != null && !dataGridView1.CurrentRow.IsNewRow)
            {
                DataGridViewRow row = dataGridView1.CurrentRow;
                txtUsername.Text = row.Cells["Username"].Value?.ToString() ?? "";
                txtPassword.Text = row.Cells["Password"].Value?.ToString() ?? "";
                txtEmail.Text = row.Cells["Email"].Value?.ToString() ?? "";
                chkIsActive.Checked = Convert.ToBoolean(row.Cells["IsActive"].Value);
            }
        }
  1. ClearInputs() 函数

功能:清空所有输入控件

清理范围:

清空用户名、密码、邮箱文本框

重置激活状态复选框为选中状态

复制代码
        private void ClearInputs()
        {
            txtUsername.Clear();
            txtPassword.Clear();
            txtEmail.Clear();

            chkIsActive.Checked = true;
        }

二、所有源码

UserService.cs文件源码

复制代码
using System;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace DatabaseHelper
{
    public class UserService
    {
        //private string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\mydb.mdf;Integrated Security=True;Connect Timeout=30";
        private string connectionString = @"Data Source = (LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\a\Desktop\APP_C#\16_sqlserver\DatabaseHelper\DatabaseHelper\App_Data\mydb.mdf;
        Integrated Security=True;Connect Timeout=30";

        // 创建user表(如果不存在)
        public void CreateUserTableIfNotExists()
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    string createTableSql = @"
                IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='user' AND xtype='U')
                BEGIN
                    CREATE TABLE [user] (
                        Id INT IDENTITY(1,1) PRIMARY KEY,
                        Username NVARCHAR(50) NOT NULL UNIQUE,
                        Password NVARCHAR(100) NOT NULL,
                        Email NVARCHAR(100),
                        CreatedDate DATETIME NOT NULL DEFAULT GETDATE(),
                        LastLogin DATETIME NULL,
                        IsActive BIT NOT NULL DEFAULT 1
                    )
                    PRINT 'User表创建成功!'
                END";

                    using (SqlCommand command = new SqlCommand(createTableSql, connection))
                    {
                        command.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"创建表失败:{ex.Message}");
            }
        }

        // 增加用户
        public bool AddUser(string username, string password, string email)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    string insertSql = @"
                INSERT INTO [user] (Username, Password, Email) 
                VALUES (@Username, @Password, @Email)";

                    using (SqlCommand command = new SqlCommand(insertSql, connection))
                    {
                        command.Parameters.AddWithValue("@Username", username);
                        command.Parameters.AddWithValue("@Password", password);
                        command.Parameters.AddWithValue("@Email", string.IsNullOrEmpty(email) ? DBNull.Value : (object)email);
                      

                        int rowsAffected = command.ExecuteNonQuery();
                        return rowsAffected > 0;
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                if (sqlEx.Number == 2627) // 唯一约束冲突
                {
                    throw new Exception("用户名已存在!");
                }
                throw new Exception($"添加用户失败:{sqlEx.Message}");
            }
            catch (Exception ex)
            {
                throw new Exception($"添加用户失败:{ex.Message}");
            }
        }

        // 删除用户
        public bool DeleteUser(int userId)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    string deleteSql = "DELETE FROM [user] WHERE Id = @Id";

                    using (SqlCommand command = new SqlCommand(deleteSql, connection))
                    {
                        command.Parameters.AddWithValue("@Id", userId);

                        int rowsAffected = command.ExecuteNonQuery();
                        return rowsAffected > 0;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"删除用户失败:{ex.Message}");
            }
        }

        // 修改用户
        public bool UpdateUser(int userId, string username, string password, string email, bool isActive)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    string updateSql = @"
                UPDATE [user] 
                SET Username = @Username, 
                    Password = @Password, 
                    Email = @Email, 
                    IsActive = @IsActive
                WHERE Id = @Id";

                    using (SqlCommand command = new SqlCommand(updateSql, connection))
                    {
                        command.Parameters.AddWithValue("@Id", userId);
                        command.Parameters.AddWithValue("@Username", username);
                        command.Parameters.AddWithValue("@Password", password);
                        command.Parameters.AddWithValue("@Email", string.IsNullOrEmpty(email) ? DBNull.Value : (object)email);                
                        command.Parameters.AddWithValue("@IsActive", isActive);

                        int rowsAffected = command.ExecuteNonQuery();
                        return rowsAffected > 0;
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                if (sqlEx.Number == 2627)
                {
                    throw new Exception("用户名已存在!");
                }
                throw new Exception($"更新用户失败:{sqlEx.Message}");
            }
            catch (Exception ex)
            {
                throw new Exception($"更新用户失败:{ex.Message}");
            }
        }

        // 查询所有用户
        public DataTable GetAllUsers()
        {
            DataTable dataTable = new DataTable();

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    string selectSql = @"
                SELECT 
                    Id,
                    Username,
                    Password,
                    Email,
                    CreatedDate,
                    LastLogin,
                    IsActive
                FROM [user] 
                ORDER BY Id";

                    using (SqlCommand command = new SqlCommand(selectSql, connection))
                    using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                    {
                        adapter.Fill(dataTable);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"查询用户失败:{ex.Message}");
            }

            return dataTable;
        }

        // 根据ID查询用户
        public DataTable GetUserById(int userId)
        {
            DataTable dataTable = new DataTable();

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    string selectSql = "SELECT * FROM [user] WHERE Id = @Id";

                    using (SqlCommand command = new SqlCommand(selectSql, connection))
                    {
                        command.Parameters.AddWithValue("@Id", userId);

                        using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                        {
                            adapter.Fill(dataTable);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"查询用户失败:{ex.Message}");
            }

            return dataTable;
        }

        // 根据用户名查询用户
        public DataTable GetUserByUsername(string username)
        {
            DataTable dataTable = new DataTable();

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    string selectSql = "SELECT * FROM [user] WHERE Username LIKE @Username";

                    using (SqlCommand command = new SqlCommand(selectSql, connection))
                    {
                        command.Parameters.AddWithValue("@Username", $"%{username}%");

                        using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                        {
                            adapter.Fill(dataTable);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"查询用户失败:{ex.Message}");
            }

            return dataTable;
        }
    }
}

Form1.cs文件源码

复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DatabaseHelper
{
    public partial class Form1 : Form
    {

        private UserService userService = new UserService();
        public Form1()
        {
            InitializeComponent();
            InitializeDatabase();
            LoadUserData();
        }

        private void InitializeDatabase()
        {
            try
            {
                //userService.CreateUserTableIfNotExists();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"数据库初始化失败:{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 添加用户
        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtUsername.Text) || string.IsNullOrWhiteSpace(txtPassword.Text))
                {
                    MessageBox.Show("用户名和密码不能为空!", "警告",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                bool success = userService.AddUser(
                    txtUsername.Text.Trim(),
                    txtPassword.Text,
                    txtEmail.Text.Trim()
                );

                if (success)
                {
                    MessageBox.Show("用户添加成功!", "成功",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearInputs();
                    LoadUserData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 更新用户
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null)
            {
                MessageBox.Show("请先选择要修改的用户!", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            try
            {
                int userId = Convert.ToInt32(dataGridView1.CurrentRow.Cells["Id"].Value);

                bool success = userService.UpdateUser(
                    userId,
                    txtUsername.Text.Trim(),
                    txtPassword.Text,
                    txtEmail.Text.Trim(),

                    chkIsActive.Checked
                );

                if (success)
                {
                    MessageBox.Show("用户更新成功!", "成功",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearInputs();
                    LoadUserData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 删除用户
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null)
            {
                MessageBox.Show("请先选择要删除的用户!", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var result = MessageBox.Show("确定要删除这个用户吗?", "确认删除",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                try
                {
                    int userId = Convert.ToInt32(dataGridView1.CurrentRow.Cells["Id"].Value);
                    bool success = userService.DeleteUser(userId);

                    if (success)
                    {
                        MessageBox.Show("用户删除成功!", "成功",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadUserData();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        // 搜索用户
        private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable users;
                if (string.IsNullOrWhiteSpace(txtSearch.Text))
                {
                    users = userService.GetAllUsers();
                }
                else
                {
                    users = userService.GetUserByUsername(txtSearch.Text.Trim());
                }
                dataGridView1.DataSource = users;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 刷新数据
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadUserData();
        }

        // 加载用户数据
        private void LoadUserData()
        {
            try
            {
                DataTable users = userService.GetAllUsers();
                dataGridView1.DataSource = users;

                // 设置列标题
                if (dataGridView1.Columns.Count > 0)
                {
                    dataGridView1.Columns["Id"].HeaderText = "ID";
                    dataGridView1.Columns["Username"].HeaderText = "用户名";
                    dataGridView1.Columns["Password"].HeaderText = "密码";
                    dataGridView1.Columns["Email"].HeaderText = "邮箱";
                    dataGridView1.Columns["CreatedDate"].HeaderText = "创建时间";
                    dataGridView1.Columns["LastLogin"].HeaderText = "最后登录";
                    dataGridView1.Columns["IsActive"].HeaderText = "是否激活";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败:{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // DataGridView选择行变化事件
        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow != null && !dataGridView1.CurrentRow.IsNewRow)
            {
                DataGridViewRow row = dataGridView1.CurrentRow;
                txtUsername.Text = row.Cells["Username"].Value?.ToString() ?? "";
                txtPassword.Text = row.Cells["Password"].Value?.ToString() ?? "";
                txtEmail.Text = row.Cells["Email"].Value?.ToString() ?? "";
                chkIsActive.Checked = Convert.ToBoolean(row.Cells["IsActive"].Value);
            }
        }

        // 清空输入框
        private void ClearInputs()
        {
            txtUsername.Clear();
            txtPassword.Clear();
            txtEmail.Clear();

            chkIsActive.Checked = true;
        }
    }
}

三、效果演示

可以进行用户的添加,删除,修改和查询

相关推荐
sukalot2 小时前
windows显示驱动开发-IddCx 1.10 及更高版本的更新
windows·驱动开发
一只学java的小汉堡3 小时前
RabbitMQ 在 Windows 环境下启动失败的完整解决方案
windows·分布式·rabbitmq
说私域5 小时前
开源AI大模型、AI智能名片与S2B2C商城小程序:用户需求满足的底层逻辑与实践路径
人工智能·小程序·开源
安当加密5 小时前
如何利用开源库和安全芯片设计fido令牌
网络·安全·开源
大飞pkz6 小时前
【设计模式】观察者模式
开发语言·观察者模式·设计模式·c#
唐青枫6 小时前
深入掌握 FluentMigrator:C#.NET 数据库迁移框架详解
c#·.net
weixin_511222806 小时前
GameObject 常见类型详解 -- 按钮(BUTTON)
开源
李宥小哥7 小时前
C#基础08-面向对象
开发语言·c#
李宥小哥7 小时前
C#基础07-类与对象
服务器·数据库·c#