using Soul2.Tools.General; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Soul2.Tools.sql { /// /// SQL语句简单生成器 /// public class SqlBuilder { private class WhereItem { public string Key { get; set; } public string Value { get; set; } public WhereItem(string key, string value) { Key = key; Value = value; } } private List _where; private List _select; private string _tbName; private List _isNullList; private string _lastJoin; public SqlBuilder(string tbName) { _tbName = tbName; _where = new List(); _select = new List(); _isNullList = new List(); } public SqlBuilder Where(string whichCol, string whatValue) { _where.Add(new WhereItem(whichCol, whatValue)); return this; } public SqlBuilder Select(string select) { _select.Add(select); return this; } public SqlBuilder IsNull(string col) { _isNullList.Add($"{col} is null"); return this; } public SqlBuilder IsNotNull(string col) { _isNullList.Add($"{col} is not null"); return this; } public SqlBuilder Last(string lastSql) { _lastJoin = lastSql; return this; } public string Build() { var select = "*"; if (_select.Count > 0) { select = string.Join(", ", _select); } var sql = $"select {select} from {_tbName}"; if (_where.Count > 0) { var whereBuilder = new StringBuilder(); foreach (var item in _where) { if (_where.IndexOf(item) != 0) { whereBuilder.Append(" and "); } whereBuilder.Append($"{item.Key} = @{item.Key}"); } sql += $" where {whereBuilder}"; } if (_isNullList.Count > 0) { foreach (var item in _isNullList) { sql += $" {item}"; } } sql += _lastJoin; return sql; } } }