C#: mysql增删改查的封装类的简单实现

默认已安装mysql

首先要添加 Mysql.Data引用

先安装一个mysql-connector-net插件:
安装一切默认就行

在mysql中建一个表,加 utf8 防止中文乱码

create table if not exists users (
id int auto_increment primary key comment '用户ID',
username varchar(32) comment '用户名',
pwd varchar(32) comment '用户密码',
sex char(8) comment '用户性别',
age int comment '年龄',
email varchar(32) comment '邮箱',
dtime datetime DEFAULT CURRENT_TIMESTAMP comment '创建时间'
) charset=utf8;

之后在VS项目中添加引用Mysql.Data

表模板类
namespace ASP.App_Code.entity
{
    public class UserEntity
    {
        private int id;
        private string username;
        private string pwd;
        private string sex;
        private int age;
        private string email;
        private string dtime;

        public UserEntity(int id, string username, string pwd, string sex, int age, string email, string dtime) {
            this.id = id;
            this.username = username;
            this.pwd = pwd;
            this.sex = sex;
            this.age = age;
            this.email = email;
            this.dtime = dtime;
        }

        public UserEntity(string username, string pwd, string sex, int age, string email, string dtime) {
            this.username = username;
            this.pwd = pwd;
            this.sex = sex;
            this.age = age;
            this.email = email;
            this.dtime = dtime;
        }

        public int Id { get => id; set => id = value; }
        public string Username { get => username; set => username = value; }
        public string Pwd { get => pwd; set => pwd = value; }
        public string Sex { get => sex; set => sex = value; }
        public int Age { get => age; set => age = value; }
        public string Email { get => email; set => email = value; }
        public string Dtime { get => dtime; set => dtime = value; }

        public override string ToString() {
            return id +",'"+ username + "','" + pwd + "','" + sex + "'," + age + ",'" + email + "'";
        }
    }
}
数据库帮助类
using MySql.Data.MySqlClient;
using System.Data;

namespace ASP.App_Code.utils
{
    public class DbUtil
    {
        public const string CONN_STRING = "server=localhost;port=3306;database=dbname;" +
    "user=root;password=123456;charset=utf8";
        private DbUtil() { }
        private class Holder
        {
            internal static readonly MySqlConnection conn = new MySqlConnection(CONN_STRING);
        }
        public static MySqlConnection GetConn() {
            return Holder.conn;
        }
        public static void close() {
            GetConn().Close();
        }
        public static void close(MySqlDataReader reader) {
            reader.Close();
            close();
        }
        public static MySqlCommand GetCommand(string command) {
            if (GetConn().State != ConnectionState.Open) {
                GetConn().Open();
            }
            return new MySqlCommand(command, GetConn());
        }

        public static MySqlCommand GetCommand(string command, params object[] args) {
            MySqlCommand cmd = GetCommand(command);
            for (int i = 0; i < args.Length; i++) {
                cmd.Parameters.Add(new MySqlParameter("@" + i, args[i]));
            }
            return cmd;
        }
    }
}

dao层对象

using System.Collections.Generic;
using ASP.App_Code.entity;
using ASP.App_Code.utils;
using MySql.Data.MySqlClient;

namespace ASP.App_Code.dao
{
    public class UserDao
    {
        public static readonly string TABLE = "users";
        private static UserDao dao = new UserDao();
        private UserDao() { }
        public static UserDao Instance() {
            return dao;
        }
        public int Insert(UserEntity entity) {
            MySqlCommand cmd = DbUtil.GetCommand(
                   "insert into " + TABLE + " (id,username,pwd,sex,age,email) values (" + entity.ToString() + ")");
            int affectRow = cmd.ExecuteNonQuery();
            DbUtil.close();
            return affectRow;
        }
        public int RemoveById(int id) {
            MySqlCommand cmd = DbUtil.GetCommand(
                    "delete from " + TABLE + " where id=@0"
                , id);
            int affectRow = cmd.ExecuteNonQuery();
            DbUtil.close();
            return affectRow;
        }
        public UserEntity ReadById(int id) {
            MySqlCommand cmd = DbUtil.GetCommand("select * from " + TABLE + " where id=" + id);
            MySqlDataReader reader = cmd.ExecuteReader();
            UserEntity entity = null;
            if (reader.Read()) {
                entity = new UserEntity(reader.GetInt32("id"),
                    reader.GetString("username"),
                    reader.GetString("pwd"),
                    reader.GetString("sex"),
                    reader.GetInt32("age"),
                    reader.GetString("email"),
                    reader.GetDateTime("dtime").ToString("yyyy-MM-dd hh:mm:ss")
                    );
            }
            DbUtil.close(reader);
            return entity;
        }
        public UserEntity ReadByUsername(string username) {
            MySqlCommand cmd = DbUtil.GetCommand("select * from " + TABLE + " where username=@0", username);
            MySqlDataReader reader = cmd.ExecuteReader();
            UserEntity entity = null;
            if (reader.Read()) {
                entity = new UserEntity(reader.GetInt32("id"),
                    reader.GetString("username"),
                    reader.GetString("pwd"),
                    reader.GetString("sex"),
                    reader.GetInt32("age"),
                    reader.GetString("email"),
                    reader.GetDateTime("dtime").ToString("yyyy-MM-dd hh:mm:ss")
                    );
            }
            DbUtil.close(reader);
            return entity;
        }
        public List<UserEntity> ReadAll() {
            MySqlCommand cmd = DbUtil.GetCommand("select * from " + TABLE);
            MySqlDataReader reader = cmd.ExecuteReader();
            List<UserEntity> list = new List<UserEntity>();
            while (reader.Read()) {
                list.Add(new UserEntity(reader.GetInt32("id"),
                    reader.GetString("username"),
                    reader.GetString("pwd"),
                    reader.GetString("sex"),
                    reader.GetInt32("age"),
                    reader.GetString("email"),
                    reader.GetDateTime("dtime").ToString("yyyy-MM-dd hh:mm:ss")
                    ));
            }
            DbUtil.close(reader);
            list.Sort((o1, o2) => o2.Dtime.CompareTo(o1.Dtime));
            return list;
        }
        public int Update(UserEntity entity) {
            string setStr = "username='" + entity.Username + "'," +
                "pwd='" + entity.Pwd + "'," +
                "sex='" + entity.Sex + "'," +
                "age=" +entity.Age+"," +
                "email='" + entity.Email + "'";
            int affectRow = DbUtil.GetCommand(
                    "update " + TABLE + " set " + setStr + " where id=@0"
                , entity.Id).ExecuteNonQuery();
            DbUtil.close();
            return affectRow;
        }
    }
}

简单的功能完成!
如果要完善的话就是要在增改时将一些特定的字符全部给过滤掉,不然会报数据库错误

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# VS2012 86系统 mysql-5.5.27-win32 功能:利用动软代码生成器 从 数据库表或者视图中生成 的三层结构代码 实现 数据增删改查。 如果可以,请下载资源中 修改 的动软代码生成器 C#模板生成 1、由于之前使用 动软生成 java 网页源码,比较成功,此处编写C#程序时沿用,感觉更加适合。 2、直接调用动软的相关dll和生成的三层代码,可以较快的实现增删改查操作。 3、由于一些dll版本的问题及动软生成器自身的一些不完善,产生了一些问题并查找了挺久,所以把可以实现的版本发布出来共享。 前提: 使用的是 mysql数据库时才可能会出现以下问题 问题: 1、MySql.Data.dll 必须是5.6.1以上版本,否则会出现 “向信号量添加给定计数将导致其超出它的最大计数” 的问题。 2、动软代码生成时,必须增加该命名空间 using MySql.Data.MySqlClient; 3、动软代码必须修改 “工具”-“选项”弹出窗 后,点击 ”代码生成设置“-”字段型映射“-”参数符号“中删除 mysql @,添加mysql ? 4、如果不修改3的设置,在增删改时 参数设置会失败。 5、mysql保存或者修改时,中文会出现乱码,这时必须 在DbHelperMySQL的 连接字中增加Charset=utf8;即 protected static string connectionString = "Server=localhost;User Id=root;Password=root;Persist Security Info=True;Database=mnzfz;Charset=utf8;"; 6、如果要在局域网中远程访问,请 修改 mysql 权限:grant select,update,insert,delete on *.* to 'root'@'192.168.0.1' identified by "123456";
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值