C# MySqlHelp类 "DbModel.MySql"数据库操作类
以前做易语言/PHP的. 最近刚入门C#, 就简单的封装了一个类库, 边学边玩才容易学到东西嘛, 比起sqlserver, 我还是觉得mysql更加有亲切感;
于是模仿ThinkPHP编写了一个”MySql”数据库操作类.
东西做的比较简单, 学习过程中也有大佬指导了一些问题. 在此非常感谢
这个类库应该来说还有一些问题需要解决, 异常捕捉什么的. 不懂怎么弄. 欢迎热心大佬们指正调教
此类库用到了 MySql.Data.dll
- 下载mysql.data.dll
- 下载完整项目
数据表
DROP TABLE IF EXISTS `table_user`;
CREATE TABLE `table_user` (
`userid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`userid`)
)
内裤(类库)代码
using System;
using System.Collections;
using MySql.Data.MySqlClient;
using System.Data;
namespace DbModel
{
public class MySQL
{
protected string m_table, m_where, m_field = "*", m_limit, m_group, m_order, m_having, m_alias, m_prefix, m_comment, m_distinct;
protected bool m_fetchSql = false;
public string LastSql = ""; //最后生成的SQL
protected ArrayList m_join = new ArrayList(), m_union = new ArrayList();
protected Hashtable m_data = new Hashtable();
public Int64 AffectCount { get; protected set; }
public Int64 RecordCount { get; protected set; }
public Int64 FieldCount { get; protected set; }
public string ConnectionString;
public MySqlConnection Connection;
public MySqlCommand Command;
public string Exception;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="table"></param>
/// <param name="prefix"></param>
public MySQL(string table, string prefix = "")
{
this.m_table = table;
this.m_prefix = prefix;
}
/// <summary>
/// 置表名
/// </summary>
/// <param name="table"></param>
/// <param name="alias">default null</param>
/// <returns>DbModel</returns>
public MySQL Table(String table, String alias = null)
{
this.m_table = table;
if (alias != null)
{
this.m_alias = " AS "+alias;
}
return this;
}
/// <summary>
/// 置选取字段
/// </summary>
/// <param name="field"></param>
/// <returns>DbModel</returns>
public MySQL Field(String field = "*")
{
this.m_field = field;
return this;
}
/// <summary>
/// 设置表别名
/// </summary>
/// <param name="alias"></param>
/// <returns></returns>
public MySQL Alias(String alias)
{
this.m_alias = " AS " + alias;
return this;
}
/// <summary>
/// 查询条件
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public MySQL Where(String where)
{
this.m_where = where;
return this;
}
/// <summary>
/// 排序方法
/// </summary>
/// <param name="order">如 user_id [desc/asc]</param>
/// <returns></returns>
public MySQL Order(String order)
{
this.m_order = " ORDER BY " + order;
return this;
}
/// <summary>
/// 设置表名前缀, 对所有表有效。如果前缀是“table_”那么需要加前缀的表前后加两个下划线“__user__”,就会得到“table_user”
/// </summary>
/// <param name="prefix"></param>
/// <returns></returns>
public MySQL Prefix(String prefix)
{
this.m_prefix = prefix;
return this;
}
/// <summary>
/// 选取部分数据
/// </summary>
/// <param name="start">开始位置,默认为第一条, 如果留空参数2则直接"LIMIT start"</param>
/// <param name="num">选取数量, 默认为0</param>
/// <returns></returns>
public MySQL Limit(int start = 0, int num = 0)
{
if (num == 0)
{
this.m_limit = " LIMIT " + Convert.ToString(start);
}
else
{
this.m_limit = " LIMIT " + Convert.ToString(start) + ", " + Convert.ToString(num);
}
return this;
}
/// <summary>
/// 分页,本方法等同limit
/// </summary>
/// <param name="page">第N页</param>
/// <param name="showNum">每页显示数量</param>
/// <returns></returns>
public MySQL Page(int page = 1, int showNum = 1000)
{
this.Limit((page-1) * showNum, showNum);
return this;
}
/// <summary>
/// 分组条件(相当于where),配合group使用(group by)
/// </summary>
/// <param name="having"></param>
/// <returns></returns>
public MySQL Having(String having)
{
this.m_having = " HAVING " + having;
return this;
}
/// <summary>
/// 分组
/// </summary>
/// <param name="group"></param>
/// <returns></returns>
public MySQL Group(String group)
{
this.m_group = " GROUP BY " + group;
return this;
}
/// <summary>
/// 连接多条SQL(多条SQL查询结果合并)
/// </summary>
/// <param name="sql"></param>
/// <param name="all">是否保留全部, 默认false (union / union all)</param>
/// <param name="clear">是否清空</param>
/// <returns></returns>
public MySQL Union(string sql, bool all = false, bool clear = false)
{
if (clear)
{
this.m_union.Clear();
}
this.m_union.Add((all == true ? "union all " : "union ") + sql);
return this;
}
/// <summary>
/// 关联多个表
/// </summary>
/// <param name="join">例:LEFT JOIN __user__ on 1 = 1</param>
/// <param name="clear">是否清除原先的join</param>
/// <returns></returns>
public MySQL Join(String join, bool clear = false)
{
if (clear)
{
this.m_join.Clear();
}
this.m_join.Add(join);
return this;
}
/// <summary>
/// 注释
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public MySQL Comment(string text)
{
this.m_comment = " /* " + text + " */ ";
return this;
}
/// <summary>
/// 唯一
/// </summary>
/// <param name="distinct"></param>
/// <returns></returns>
public MySQL Distinct(bool distinct)
{
this.m_distinct = (distinct == false ? "" : "DISTINCT ");
return this;
}
/// <summary>
/// 获取SQL, 如果为True. Select/Add/Save/Del 将返回SQL语句, 并且不执行
/// </summary>
/// <param name="fetch"></param>
/// <returns></returns>
public MySQL FetchSql(bool fetch)
{
this.m_fetchSql = fetch;
return this;
}
/// <summary>
/// 绑定字段
/// </summary>
/// <param name="field"></param>
/// <param name="value"></param>
public MySQL Data(string field, object value)
{
string temp = "";
if (value == null)
{
temp = "null";
}
else
{
switch (value.GetType().Name)
{
case "String":
temp = "'" + this.FilterSQL(value.ToString()) + "'";
break;
case "DateTime":
temp = "'" + value.ToString() + "'";
break;
default:
temp = value.ToString();
break;
}
}
//如果存在:删除
if (this.m_data.ContainsKey(field))
{
this.m_data.Remove(field);
this.m_data.Add(field, temp);
return this;
}
//新增
this.m_data.Add(field, temp);
return this;
}
/// <summary>
/// 过滤SQL
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private string FilterSQL(string value)
{
value.Replace("/", "\\/").Replace("\"", "\\\"").Replace("'", "\\'");
return value;
}
/// <summary>
/// 重置所有字段信息
/// </summary>
protected void Clear()
{
this.m_field = "*";
this.m_join.Clear();
this.m_union.Clear();
this.m_data.Clear();
this.m_group = this.m_having = this.m_order = this.m_where = this.m_distinct = this.m_order = this.m_limit = this.LastSql = this.m_comment = "";
}
/// <summary>
/// 打开连接(连接数据库)
/// </summary>
/// <param name="ConnectionString"></param>
/// <returns></returns>
public bool Open(string ConnectionString=null)
{
if (ConnectionString != null)
{
this.ConnectionString = ConnectionString;
}
Connection = new MySqlConnection(this.ConnectionString);
try
{
this.Connection.Open();
this.Command = this.Connection.CreateCommand();
return true;
}
catch(MySqlException e)
{
this.Exception = e.ToString();
return false;
}
}
/// <summary>
/// 关闭连接
/// </summary>
public void Close()
{
this.Connection.Close();
}
/// <summary>
/// 执行SQL (只能执行 insert、update、delete),
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public bool Execute(string sql = "")
{
this.Command.CommandText = sql;
this.AffectCount = this.Command.ExecuteNonQuery();
return this.AffectCount > 0;
}
/// <summary>
/// 查询第一列第一条记录
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public object QueryOne(string sql)
{
this.Command.CommandText = sql;
return this.Command.ExecuteScalar();
}
/// <summary>
/// 查询SQL
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public DataTable Query(string sql)
{
this.Command.CommandText = sql;
MySqlDataAdapter adpter = new MySqlDataAdapter(this.Command);
DataTable dt = new DataTable("Table");
adpter.Fill(dt);
this.RecordCount = dt.Rows.Count;
this.FieldCount = dt.Columns.Count;
return dt;
}
/// <summary>
/// 查询(select)
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
public object Select(string table = null, string where = null)
{
this.LastSql = this.GetSelectSql(table, where);
if (this.m_fetchSql)
{
return this.LastSql;
}
else
{
DataTable data = this.Query(this.LastSql);
this.Clear();
return data;
}
}
/// <summary>
/// 新增记录(插入记录 insert)
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
public object Add(string table = null)
{
this.LastSql = this.GetInsertSql(table);
if (this.m_fetchSql)
{
return this.LastSql;
}
else
{
bool ret = this.Execute(this.LastSql);
this.Clear();
return ret;
}
}
/// <summary>
/// 保存记录(更新记录 update)
/// </summary>
/// <param name="table"></param>
/// <param name="where"></param>
/// <returns></returns>
public object Save(string table = null, string where = null)
{
this.LastSql = this.GetUpdateSql(table, where);
if (this.m_fetchSql)
{
return this.LastSql;
}
else
{
bool ret = this.Execute(this.LastSql);
this.Clear();
return ret;
}
}
/// <summary>
/// 删除记录 (delete)
/// </summary>
/// <param name="table"></param>
/// <param name="where"></param>
/// <returns></returns>
public object Delete(string table = null, string where = null)
{
this.LastSql = this.GetDeleteSql(table, where);
if (this.m_fetchSql)
{
return this.LastSql;
}
else
{
bool ret = this.Execute(this.LastSql);
this.Clear();
return ret;
}
}
/// <summary>
/// 获取查询记录语句
/// </summary>
/// <param name="table"></param>
/// <param name="where"></param>
/// <returns></returns>
protected string GetSelectSql(string table = null, string where = null)
{
table = table ?? this.m_table;
where = " WHERE " + (where ?? this.m_where);
/*
* 0: 唯一
* 1:选取字段
* 2:表前缀
* 3:表名
* 4:表别称
* 5:join
* 6:where
* 7:group
* 8:having
* 9:order
* 10:limit
* 11:union
* 12:注释
*/
this.LastSql = "SELECT {0}{1} FROM `{2}{3}`{4}{5}{6}{7}{8}{9}{10}{11}{12}";
//join
string join = "";
for (int i = 0; i < this.m_join.Count; i++)
{
join += " " + this.m_join[i];
}
//union
string union = "";
for (int i = 0; i < this.m_union.Count; i++)
{
union += " " + this.m_union[i];
}
string sql = string.Format(this.LastSql, this.m_distinct, this.m_field, this.m_prefix, table, this.m_alias, join, where, this.m_group, this.m_having, this.m_order, this.m_limit, union, this.m_comment);
return sql;
}
/// <summary>
/// 获取插入记录语句
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
protected string GetInsertSql(string table = null)
{
table = table ?? this.m_table;
string fields = "", values = "";
foreach (string key in this.m_data.Keys)
{
fields += "`"+key + "`, ";
values += this.m_data[key] + ", ";
}
if (fields.Length > 3)
{
fields = fields.Substring(0, fields.Length - 2);
values = values.Substring(0, values.Length - 2);
}
string sql = string.Format("INSERT INTO `{0}{1}` ({2}) VALUES({3})", this.m_prefix, table, fields, values);
return sql;
}
/// <summary>
/// 获取更新记录语句
/// </summary>
/// <param name="table"></param>
/// <param name="where"></param>
/// <returns></returns>
protected string GetUpdateSql(string table = null, string where = null)
{
table = table ?? this.m_table;
where = " WHERE " + (where ?? this.m_where);
string data = "";
foreach (string key in this.m_data.Keys)
{
data += "`" + key + "` = " + this.m_data[key] + ", ";
}
if (data.Length > 3)
{
data = data.Substring(0, data.Length - 2);
}
string sql = string.Format("UPDATE `{0}{1}` SET {2}{3}", this.m_prefix, table, data, where);
return sql;
}
/// <summary>
/// 获取删除记录语句
/// </summary>
/// <param name="table"></param>
/// <param name="where"></param>
/// <returns></returns>
protected string GetDeleteSql(string table = null, string where = null)
{
table = table ?? this.m_table;
where = " WHERE " + (where ?? this.m_where);
string sql = string.Format("DELETE FROM `{0}{1}`{2}{3}", this.m_prefix, table, where, this.m_limit);
return sql;
}
}
}
测试代码
using System;
using System.Data;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DbModel;
namespace Test
{
class Program
{
static void Main(string[] args)
{
DbModel.MySQL m = new DbModel.MySQL("user", "table_");
m.ConnectionString = "server=localhost;User Id=root;password=;Database=test;Charset=utf8";
m.Open();
//m.Open("server=localhost;User Id=root;password=;Database=test;Charset=utf8");
bool fetch = false; //返回SQL字符串, 并不执行
Console.WriteLine("新增测试");
m.Data("username", "剑齿虎");
m.Data("password", "123456");
m.Data("userid", null);
Console.WriteLine(m.FetchSql(fetch).Add());
m.Data("username", "剑齿虎");
m.Data("password", "123456");
m.Data("userid", 1);
Console.WriteLine(m.FetchSql(fetch).Add());
Console.WriteLine("影响行数:" + m.AffectCount);
Console.WriteLine("\n\n修改测试");
m.Data("username", "yuxiaobo64@gmail.com");
Console.WriteLine(m.FetchSql(fetch).Where("userid = 1").Save());
Console.WriteLine("影响行数:" + m.AffectCount);
Console.WriteLine("\n\n查询测试");
DataTable dt = (DataTable)m.Where("1").Field("userid, username, password").Distinct(true).FetchSql(fetch).Order("username DESC").Select();
foreach (DataRow item in dt.Rows)
{
Console.WriteLine(item["userid"] + ", " + item["username"] + ", " + item["password"]);
}
Console.WriteLine("记录数量:" + m.RecordCount);
Console.WriteLine("字段数量:" + m.FieldCount);
Console.WriteLine("\n\n删除测试");
Console.WriteLine(m.FetchSql(fetch).Where("password = '123456'").Delete());
Console.WriteLine("影响行数:" + m.AffectCount);
Console.ReadKey();
}
}
}
测试结果
新增测试
True
True
影响行数:1
修改测试
True
影响行数:1
查询测试
107, 剑齿虎, 123456
1, yuxiaobo64@gmail.com, 123456
记录数量:2
字段数量:3
删除测试
True
影响行数:2
C# MySqlHelp类 "DbModel.MySql"数据库操作类的更多相关文章
- php : mysql数据库操作类演示
设计目标: 1,该类一实例化,就可以自动连接上mysql数据库: 2,该类可以单独去设定要使用的连接编码(set names XXX) 3,该类可以单独去设定要使用的数据库(use XXX): 4,可 ...
- php MySQL数据库操作类源代码
php MySQL数据库操作类源代码: <?php class MySQL{ private $host; //服务器地址 private $name; //登录账号 private $pwd; ...
- 设计模式 - 单例模式mysql数据库操作类
待续... index.php 调用方法: <?php header('Content-Type:text/html; charset=utf8'); require 'instance.php ...
- MySQL数据库操作类(PHP实现,支持连贯操作)
<?php /** * Author: suvan * CreateTime: 2018/2/27 * description: 数据库操作类(仅对接MySQL数据库,主要利用MySQLi函数) ...
- php pdo mysql数据库操作类
<?php namespace iphp\core; use iphp\App; /** * 数据库操作基类 基于pdo * @author xuen * 支持链式操作,支持参数绑定 * 说明1 ...
- C#---数据库访问通用类、Access数据库操作类、mysql类 .[转]
原文链接 //C# 数据库访问通用类 (ADO.NET)using System;using System.Collections.Generic;using System.Text;using Sy ...
- C#---数据库访问通用类、Access数据库操作类、mysql类 .
//C# 数据库访问通用类 (ADO.NET)using System;using System.Collections.Generic;using System.Text;using System. ...
- C# MySQL 数据库操作类
using System; using System.Configuration; using System.Collections; using System.Data; using MySql.D ...
- DELPHI XE MYSQL数据库操作类 MYSQLHELPER
注: 无需odbc配置 {* * MySQL Helper v1.0 * 2015.6.19 * 说明: * 这是一个操作MySQL的类,该类必须和libmysql.dll,dbxmys.dll两个文 ...
- php 封装mysql 数据库操作类
<?phpheader('content-type:text/html;charset=utf-8');//封装mysql 连接数据库php_mysql//封装mysql 连接数据库ph ...
随机推荐
- flutter中使用pubspec.yaml更改package name
在flutter 项目中使用pubspec.yaml文件进行依赖资源相关配置是常有的事 但是刚发现它可以修改name来控制项目包名称,当初创建了不同的项目名git后还到每个文件里去修改import(麻 ...
- Python潮流周刊#3:PyPI 的安全问题
你好,我是豌豆花下猫.这里记录每周值得分享的 Python 及通用技术内容,部分为英文,已在小标题注明.(标题取自其中一则分享,不代表全部内容都是该主题,特此声明.) 文章&教程 1.掌握Py ...
- 【HarmonyOS】元服务和APP的相互跳转、相互成就
[关键字] 卡片.跳转.加桌 [背景介绍] 随着鸿蒙生态的发展,各种类型的应用都已经可以在Harmony OS上无差异的运行,面对鸿蒙新兴元服务的兴起,各大厂家可能都在考虑一个问题:如果已经有AP ...
- 远程desk工具利用总结
NO.1 Todesk 根据目标软件安装情况有以下两种利用方法 1.目标机已有完整版todesk. 1)改配置文件. 老版本可替换至本地查看密码(此法在最近更新的几个版本中已经失效),新版本只可更改密 ...
- 智慧饮水系统_Android客户端
智慧饮水系统(又名:水牛 APP) 1.介绍 该项目基于 Rfid-RC522.ESP-32 进行下位机开发,硬件模块 Rfid-RC522 主要读取用户的卡号,ESP32 单片机通过 WiFi 模块 ...
- 在Transformers 中使用约束波束搜索引导文本生成
引言 本文假设读者已经熟悉文本生成领域波束搜索相关的背景知识,具体可参见博文 如何生成文本: 通过 Transformers 用不同的解码方法生成文本. 与普通的波束搜索不同,约束 波束搜索允许我们控 ...
- Docusaurus之markdown文档的vscode代码片段
需求 我是使用Docusaurus建立的个人站点,在写文档是总是要在开头配置作者.日期等等,用过Docusaurus的都应该知道. 因为每次新建一个md文档都需要重新配置,很麻烦,于是我就想能不能新建 ...
- midjourney国内版上线! 快来体验一下midjourney的强大功能
最近大火的midjourney国内版上线了!该网站对接了midjourneyAPI,以文生图.以图生图功能都支持,下面我们来体验一下它的功能. 网址:https://www.weijiwangluo. ...
- JavaWeb中Servlet、web应用和web站点的路径细节("/"究竟代表着什么)
JavaWeb中Servlet.web应用和web站点的路径细节("/"究竟代表着什么) 1 开门见山 新建一个tomcat web项目,配置tomcat的虚拟目录,取默认值(/项 ...
- FHQ-Treap的详细图解
第一部分 按值分裂的 FHQ-Treap 按值分裂的 FHQ-Treap 的典型例题是P3369 [模板]普通平衡树. 思路 FHQ-Treap 是什么? FHQ-Treap 是二叉搜索树的一种. 比 ...