博客
关于我
Net连接mysql的公共Helper类MySqlHelper.cs带MySql.Data.dll下载
阅读量:789 次
发布时间:2023-02-15

本文共 2153 字,大约阅读时间需要 7 分钟。

MySqlHelper.cs 代码解析与使用示例

1. 类概述

MySqlHelper 是一个用于简化 MySQL 数据库操作的高级辅助类,提供了一系列执行数据库命令、数据读取和参数缓存等功能。该类通过静态方法实现数据库操作,适用于多种数据库任务,如插入、更新、查询、事务管理等。

2. 主要功能概述

2.1 SQL 命令执行

  • ExecuteNonQuery:执行不返回结果的 SQL 命令,如插入、更新、删除操作。
  • ExecuteReader:执行返回结果集的 SQL 查询,返回 MySqlDataReader
  • ExecuteScalar:执行返回单一结果的 SQL 查询,返回 object
  • GetDataSet:执行返回数据集的 SQL 查询,填充 DataSet

2.2 参数管理

  • CacheParameters:将参数缓存到哈希表中,减少重复参数设置。
  • GetCachedParameters:从哈希表中获取缓存的参数集合。

2.3 事务管理

  • ExecuteTransaction:执行多个 SQL 语句作为事务,支持自动Commit和Rollback。

2.4 参数准备

  • PrepareCommand:准备 SQL 命令及其参数,确保数据库连接状态正确。

3. 使用示例

3.1 插入操作

// 示例:插入数据到 `tb_baobei` 表MySqlCommand sqlCom = new MySqlCommand();sqlCom.CommandText = "INSERT INTO `tb_baobei` (`tb_Name`,`tb_Price`,`tb_Image`,`tb_Url`)" +    " VALUES(@tb_Name,@tb_Price,@tb_Image,@tb_Url);";MySqlParameter[] commandParameters = new MySqlParameter[]{    new MySqlParameter("@tb_Name", bb.Name),    new MySqlParameter("@tb_Price", bb.Price.Trim()),    new MySqlParameter("@tb_Image", bb.Image),    new MySqlParameter("@tb_Url", bb.Url)};MySqlHelper.ExecuteNonQuery(    MySqlHelper.CommandType.Text,    MySqlHelper.ConnectionStringManager,    sqlCom.CommandText,    commandParameters);

3.2 查询操作

// 示例:登录验证public string Login(string email, string password){    MySqlCommand sqlCom = new MySqlCommand();    sqlCom.CommandText = "select * from common_members where email = @email";    MySqlParameter commandParameter = new MySqlParameter("@email", email);    MySqlDataReader reader = MySqlHelper.ExecuteReader(        MySqlHelper.ConnectionStringManager,        MySqlHelper.CommandType.Text,        sqlCom.CommandText,        commandParameter    );    if (reader.Read())    {        string pwd = reader["password"].ToString();        if (pwd.Equals(password))        {            return "1";        }        else        {            return "0";        }    }    else    {        return "-1";    }}

4. 配置文件示例

5. 注意事项

  • 数据库连接:确保提供的连接字符串正确,包括服务器地址、数据库名称、用户名和密码等信息。
  • 参数缓存:通过 CacheParameters 方法缓存常用参数,提高后续操作效率。
  • 事务管理:在多个数据库操作中使用事务时,确保 CommitRollback 正确执行。
  • 异常处理:在 ExecuteReaderExecuteScalar 方法中,使用 try/catch 结构处理可能的异常,确保资源安全释放。

通过合理使用 MySqlHelper 类,开发者可以简化数据库操作流程,提高代码复用性和效率。

转载地址:http://rtcfk.baihongyu.com/

你可能感兴趣的文章