├── file ├── logo.png └── logo-2.png ├── code └── HSQL │ ├── HSQL.Test │ ├── README.txt │ ├── UnitTestPerformance.cs │ ├── TestDataBaseModel │ │ ├── School.cs │ │ ├── Subject.cs │ │ ├── Score.cs │ │ └── Student.cs │ ├── TestViewModel │ │ └── LoginViewModel.cs │ ├── HSQL.Test.csproj │ ├── TestHelper │ │ └── UnixTime.cs │ ├── UnitTestTransaction.cs │ └── UnitTestDataBase.cs │ ├── HSQL │ ├── Attribute │ │ ├── IdentityAttribute.cs │ │ ├── ColumnAttribute.cs │ │ └── TableAttribute.cs │ ├── Model │ │ ├── OrderInfo.cs │ │ ├── Column.cs │ │ ├── Sql.cs │ │ ├── TableInfo.cs │ │ └── Parameter.cs │ ├── Utils │ │ └── OrderBy.cs │ ├── ConnectionPools │ │ ├── IConnector.cs │ │ └── Connector.cs │ ├── Const │ │ ├── PageConst.cs │ │ ├── KeywordConst.cs │ │ └── TypeOfConst.cs │ ├── Exceptions │ │ ├── DataIsNullException.cs │ │ ├── EmptySQLException.cs │ │ ├── ExpressionException.cs │ │ ├── EmptyParameterException.cs │ │ ├── ExpressionIsNullException.cs │ │ ├── SingleOrDefaultException.cs │ │ └── ConnectionStringIsEmptyException.cs │ ├── IDbSQLHelper.cs │ ├── HSQL.csproj │ ├── Base │ │ ├── DbContextBase.cs │ │ ├── QueryabelBase.cs │ │ ├── DbHelperBase.cs │ │ └── StoreBase.cs │ ├── IQueryabel.cs │ ├── Extensions │ │ ├── ExpressionExtensions.cs │ │ └── QueryabelExtensions.cs │ ├── IDbContext.cs │ ├── Factory │ │ ├── InstanceFactory.cs │ │ └── ExpressionFactory.cs │ └── HSQL.xml │ ├── HSQL.NugetTest │ ├── HSQL.NugetTest.csproj │ └── Program.cs │ ├── HSQL.MySQL │ ├── HSQL.MySQL.xml │ ├── HSQL.MySQL.csproj │ ├── MySQLConnectionPools.cs │ ├── MySQLHelper.cs │ ├── DbContext.cs │ └── MySQLQueryabel.cs │ ├── HSQL.MSSQLServer │ ├── SQLServerConnector.cs │ ├── HSQL.MSSQLServer.csproj │ ├── HSQL.MSSQLServer.xml │ ├── SQLServerConnectionPools.cs │ ├── SQLServerHelper.cs │ ├── DbContext.cs │ └── SQLServerQueryabel.cs │ └── HSQL.sln ├── LICENSE ├── .gitattributes ├── README.md └── .gitignore /file/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hexu6788/HSQL/HEAD/file/logo.png -------------------------------------------------------------------------------- /file/logo-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hexu6788/HSQL/HEAD/file/logo-2.png -------------------------------------------------------------------------------- /code/HSQL/HSQL.Test/README.txt: -------------------------------------------------------------------------------- 1 | 未解决BUG: 2 | 1. 不能查询重复参数,如:Query(x => x.Name == "transaction_1" || x.Name == "transaction_2") -------------------------------------------------------------------------------- /code/HSQL/HSQL.Test/UnitTestPerformance.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hexu6788/HSQL/HEAD/code/HSQL/HSQL.Test/UnitTestPerformance.cs -------------------------------------------------------------------------------- /code/HSQL/HSQL/Attribute/IdentityAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HSQL.Attribute 4 | { 5 | public class IdentityAttribute : System.Attribute 6 | { 7 | 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Model/OrderInfo.cs: -------------------------------------------------------------------------------- 1 | namespace HSQL.Model 2 | { 3 | public class OrderInfo 4 | { 5 | public string Field { get; set; } 6 | public string By { get; set; } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Utils/OrderBy.cs: -------------------------------------------------------------------------------- 1 | namespace HSQL.Utils 2 | { 3 | public class OrderBy 4 | { 5 | public const string ASC = "ASC"; 6 | public const string DESC = "DESC"; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Attribute/ColumnAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HSQL.Attribute 4 | { 5 | public class ColumnAttribute : System.Attribute 6 | { 7 | public string Name { get; set; } 8 | 9 | public ColumnAttribute(string name) 10 | { 11 | Name = name; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/ConnectionPools/IConnector.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data; 3 | 4 | namespace HSQL.ConnectionPools 5 | { 6 | public interface IConnector : IDisposable 7 | { 8 | ConnectorState GetState(); 9 | void SetState(ConnectorState state); 10 | IDbConnection GetConnection(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Const/PageConst.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace HSQL.Const 6 | { 7 | public class PageConst 8 | { 9 | /// 10 | /// 分页最大数量 11 | /// 12 | public new const int MaxCount = 9999999; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.NugetTest/HSQL.NugetTest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.Test/TestDataBaseModel/School.cs: -------------------------------------------------------------------------------- 1 | using HSQL.Attribute; 2 | 3 | namespace HSQL.Test.TestDataBaseModel 4 | { 5 | [Table("t_school")] 6 | public class School 7 | { 8 | [Column("id")] 9 | public string Id { get; set; } 10 | 11 | [Column("name")] 12 | public string Name { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.Test/TestViewModel/LoginViewModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace HSQL.Test.TestViewModel 6 | { 7 | public class LoginViewModel 8 | { 9 | public string Account { get; set; } 10 | public string Password { get; set; } 11 | public int Checked { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Attribute/TableAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace HSQL.Attribute 6 | { 7 | public class TableAttribute : System.Attribute 8 | { 9 | public string Name { get; set; } 10 | 11 | public TableAttribute(string name) 12 | { 13 | Name = name; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Exceptions/DataIsNullException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HSQL.Exceptions 4 | { 5 | public class DataIsNullException : Exception 6 | { 7 | public DataIsNullException(string message = "异常原因:数据为空!") : base(message) 8 | { 9 | 10 | } 11 | 12 | public override string ToString() 13 | { 14 | return base.ToString(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Exceptions/EmptySQLException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HSQL.Exceptions 4 | { 5 | public class EmptySQLException : Exception 6 | { 7 | public EmptySQLException(string message = "异常原因:生成SQL语句为空!") : base(message) 8 | { 9 | 10 | } 11 | 12 | public override string ToString() 13 | { 14 | return base.ToString(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Exceptions/ExpressionException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HSQL.Exceptions 4 | { 5 | public class ExpressionException : Exception 6 | { 7 | public ExpressionException(string message = "异常原因:表达式异常!") : base(message) 8 | { 9 | 10 | } 11 | 12 | public override string ToString() 13 | { 14 | return base.ToString(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.Test/TestDataBaseModel/Subject.cs: -------------------------------------------------------------------------------- 1 | using HSQL.Attribute; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace HSQL.Test.TestDataBaseModel 7 | { 8 | [Table("t_subject")] 9 | public class Subject 10 | { 11 | [Column("id")] 12 | public string Id { get; set; } 13 | 14 | [Column("name")] 15 | public string Name { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Exceptions/EmptyParameterException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HSQL.Exceptions 4 | { 5 | public class EmptyParameterException : Exception 6 | { 7 | public EmptyParameterException(string message = "异常原因:参数为空!") : base(message) 8 | { 9 | 10 | } 11 | 12 | public override string ToString() 13 | { 14 | return base.ToString(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Exceptions/ExpressionIsNullException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HSQL.Exceptions 4 | { 5 | public class ExpressionIsNullException : Exception 6 | { 7 | public ExpressionIsNullException(string message = "异常原因:表达式为空!") : base(message) 8 | { 9 | 10 | } 11 | 12 | public override string ToString() 13 | { 14 | return base.ToString(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Exceptions/SingleOrDefaultException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HSQL.Exceptions 4 | { 5 | public class SingleOrDefaultException : Exception 6 | { 7 | public SingleOrDefaultException(string message = "异常原因:出现多条实例!") : base(message) 8 | { 9 | 10 | } 11 | 12 | public override string ToString() 13 | { 14 | return base.ToString(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Model/Column.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace HSQL.Model 6 | { 7 | public class Column 8 | { 9 | public Column() { } 10 | public Column(string name, object value) 11 | { 12 | Name = name; 13 | Value = value; 14 | } 15 | public string Name { get; set; } 16 | public object Value { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.NugetTest/Program.cs: -------------------------------------------------------------------------------- 1 | using HSQL.MySQL; 2 | using System; 3 | using System.Linq; 4 | 5 | namespace HSQL.NugetTest 6 | { 7 | class Program 8 | { 9 | static void Main(string[] args) 10 | { 11 | IDbContext dbContext = new DbContext("127.0.0.1", "test", "root", "123456"); 12 | var list = dbContext.Query("SELECT * FROM t_student;"); 13 | 14 | Console.WriteLine("Hello World!"); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Exceptions/ConnectionStringIsEmptyException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HSQL.Exceptions 4 | { 5 | public class ConnectionStringIsEmptyException : Exception 6 | { 7 | public ConnectionStringIsEmptyException(string message = "异常原因:连接字符串为空或错误!") : base(message) 8 | { 9 | 10 | } 11 | 12 | public override string ToString() 13 | { 14 | return base.ToString(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Const/KeywordConst.cs: -------------------------------------------------------------------------------- 1 | namespace HSQL.Const 2 | { 3 | public class KeywordConst 4 | { 5 | public new const string Equals = "Equals"; 6 | public const string IN = "IN"; 7 | public const string LIKE = "LIKE"; 8 | public const string Contains = "Contains"; 9 | public const string AND = "AND"; 10 | public const string OR = "OR"; 11 | public const string ASC = "ASC"; 12 | public const string DESC = "DESC"; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Model/Sql.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace HSQL.Model 4 | { 5 | public class Sql 6 | { 7 | public Sql() 8 | { 9 | Parameters = new List(); 10 | } 11 | public Sql(string commandText) 12 | { 13 | CommandText = commandText; 14 | Parameters = new List(); 15 | } 16 | 17 | public string CommandText { get; set; } 18 | public List Parameters { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.Test/TestDataBaseModel/Score.cs: -------------------------------------------------------------------------------- 1 | using HSQL.Attribute; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace HSQL.Test.TestDataBaseModel 7 | { 8 | [Table("t_score")] 9 | public class Score 10 | { 11 | [Column("id")] 12 | public string Id { get; set; } 13 | 14 | [Column("student_id")] 15 | public string StudentId { get; set; } 16 | 17 | [Column("subject_id")] 18 | public string SubjectId { get; set; } 19 | 20 | [Column("value")] 21 | public decimal Value { get; set; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.Test/TestDataBaseModel/Student.cs: -------------------------------------------------------------------------------- 1 | using HSQL.Attribute; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace HSQL.Test.TestDataBaseModel 7 | { 8 | [Table("t_student")] 9 | public class Student 10 | { 11 | [Column("id")] 12 | public string Id { get; set; } 13 | 14 | [Column("name")] 15 | public string Name { get; set; } 16 | 17 | [Column("age")] 18 | public int Age { get; set; } 19 | 20 | [Column("school_id")] 21 | public string SchoolId { get; set; } 22 | 23 | [Column("birthday")] 24 | public long Birthday { get; set; } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/IDbSQLHelper.cs: -------------------------------------------------------------------------------- 1 | using HSQL.Model; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Reflection; 5 | 6 | namespace HSQL 7 | { 8 | public interface IDbSQLHelper 9 | { 10 | int ExecuteNonQuery(bool isNewConnection, string commandText, params IDbDataParameter[] parameters); 11 | object ExecuteScalar(string commandText, params IDbDataParameter[] parameters); 12 | List ExecuteList(string commandText, params IDbDataParameter[] parameters); 13 | List ExecuteList(string commandText, params IDbDataParameter[] parameters); 14 | IDbDataParameter[] Convert(List parameters); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.Test/HSQL.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.MySQL/HSQL.MySQL.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | HSQL.MySQL 5 | 6 | 7 | 8 | 9 | 构建数据库对象 10 | 11 | 服务器地址 12 | 数据库名称 13 | 用户名 14 | 密码 15 | 连接池连接数 16 | 是否在控制台输出Sql语句 17 | 18 | 19 | 20 | 连接池 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/HSQL.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | true 6 | 1.0.0.16 7 | HSQL 是一种轻量级的基于 .NET 的 ORM 框架 8 | https://github.com/hexu6788/HSQL 9 | https://github.com/hexu6788/HSQL 10 | HSQL-Standard 11 | HSQL 12 | 何旭 13 | 1.0.0.16 14 | 1.0.0.16 15 | 16 | 17 | 18 | D:\HSQL\code\HSQL\HSQL\HSQL.xml 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.MSSQLServer/SQLServerConnector.cs: -------------------------------------------------------------------------------- 1 | using System.Data; 2 | using System.Data.SqlClient; 3 | 4 | namespace HSQL.MSSQLServer 5 | { 6 | internal class SQLServerConnector 7 | { 8 | private bool _usable; 9 | private SqlConnection _connection; 10 | 11 | 12 | internal SQLServerConnector(string connectionString) 13 | { 14 | _usable = true; 15 | _connection = new SqlConnection(connectionString); 16 | } 17 | 18 | /// 19 | /// 是否可用 20 | /// 21 | internal bool Usable { get { return _usable; } set { _usable = value; } } 22 | 23 | /// 24 | /// 获取连接对象 25 | /// 26 | /// 27 | internal SqlConnection GetConnection() 28 | { 29 | if (_connection.State == ConnectionState.Closed) 30 | { 31 | _connection.Open(); 32 | } 33 | return _connection; 34 | } 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.MSSQLServer/HSQL.MSSQLServer.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | true 6 | 1.0.0.16 7 | 何旭 8 | 何旭 9 | HSQL 10 | HSQL 是一种轻量级的基于 .NET 的 ORM 框架 11 | https://github.com/hexu6788/HSQL 12 | https://github.com/hexu6788/HSQL 13 | 1.0.0.16 14 | 15 | 16 | 17 | D:\HSQL\code\HSQL\HSQL.MSSQLServer\HSQL.MSSQLServer.xml 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.MySQL/HSQL.MySQL.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | true 6 | HSQL 是一种轻量级的基于 .NET 的 ORM 框架 7 | 何旭 8 | 何旭 9 | HSQL 10 | https://github.com/hexu6788/HSQL 11 | https://github.com/hexu6788/HSQL 12 | 1.0.0.16 13 | 1.0.0.16 14 | 1.0.0.16 15 | 16 | 17 | 18 | D:\HSQL\code\HSQL\HSQL.MySQL\HSQL.MySQL.xml 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 何旭 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/ConnectionPools/Connector.cs: -------------------------------------------------------------------------------- 1 | using System.Data; 2 | 3 | namespace HSQL.ConnectionPools 4 | { 5 | public class Connector : IConnector 6 | { 7 | 8 | private ConnectorState _state; 9 | private IDbConnection _connection; 10 | 11 | public Connector(IDbConnection connection) 12 | { 13 | _state = ConnectorState.可用; 14 | _connection = connection; 15 | } 16 | 17 | public ConnectorState GetState() 18 | { 19 | return _state; 20 | } 21 | 22 | public void SetState(ConnectorState state) 23 | { 24 | _state = state; 25 | } 26 | 27 | public void Dispose() 28 | { 29 | _state = ConnectorState.可用; 30 | } 31 | 32 | public IDbConnection GetConnection() 33 | { 34 | if (_connection.State == ConnectionState.Closed || _connection.State == ConnectionState.Broken) 35 | _connection.Open(); 36 | 37 | return _connection; 38 | } 39 | } 40 | 41 | public enum ConnectorState 42 | { 43 | 可用 = 1, 占用 = 2 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Model/TableInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Reflection; 4 | using System.Text; 5 | 6 | namespace HSQL.Model 7 | { 8 | public class TableInfo 9 | { 10 | public TableInfo() 11 | { 12 | Columns = new List(); 13 | } 14 | 15 | /// 16 | /// 表名称 17 | /// 18 | public string Name { get; set; } 19 | 20 | /// 21 | /// 使用逗号将列名进行拼接后得到的字符串 22 | /// 23 | public string ColumnsComma { get; set; } 24 | 25 | /// 26 | /// 默认排序列 27 | /// 28 | public string DefaultOrderColumnName { get; set; } 29 | public List Columns { get; set; } 30 | } 31 | 32 | public class ColumnInfo 33 | { 34 | /// 35 | /// 是否为自增列 36 | /// 37 | public bool Identity { get; set; } 38 | 39 | /// 40 | /// 列名称 41 | /// 42 | public string Name { get; set; } 43 | public PropertyInfo Property { get; set; } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.MSSQLServer/HSQL.MSSQLServer.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | HSQL.MSSQLServer 5 | 6 | 7 | 8 | 9 | 构建数据库对象 10 | 11 | 服务器地址 12 | 数据库名称 13 | 用户名 14 | 密码 15 | 连接池连接数 16 | 是否在控制台输出Sql语句 17 | 18 | 19 | 20 | 连接池 21 | 22 | 23 | 24 | 25 | 是否可用 26 | 27 | 28 | 29 | 30 | 获取连接对象 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Const/TypeOfConst.cs: -------------------------------------------------------------------------------- 1 | using HSQL.Attribute; 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace HSQL.Const 6 | { 7 | internal class TypeOfConst 8 | { 9 | internal static Type String = typeof(string); 10 | internal static Type Int = typeof(int); 11 | internal static Type UInt = typeof(uint); 12 | internal static Type Long = typeof(long); 13 | internal static Type Float = typeof(float); 14 | internal static Type Double = typeof(double); 15 | internal static Type Decimal = typeof(decimal); 16 | internal static Type DateTime = typeof(DateTime); 17 | internal static Type ByteArray = typeof(byte[]); 18 | 19 | internal static Type ListString = typeof(List); 20 | internal static Type ListInt = typeof(List); 21 | internal static Type ListLong = typeof(List); 22 | internal static Type ListFloat = typeof(List); 23 | internal static Type ListDouble = typeof(List); 24 | internal static Type ListDecimal = typeof(List); 25 | 26 | internal static Type TableAttribute = typeof(TableAttribute); 27 | internal static Type ColumnAttribute = typeof(ColumnAttribute); 28 | internal static Type IdentityAttribute = typeof(IdentityAttribute); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Base/DbContextBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Transactions; 4 | 5 | namespace HSQL.Base 6 | { 7 | public abstract class DbContextBase 8 | { 9 | /// 10 | /// 是否开启事务 11 | /// 12 | public ThreadLocal TransactionIsOpen = new ThreadLocal(() => false); 13 | 14 | /// 15 | /// SQL帮助对象 16 | /// 17 | protected IDbSQLHelper DbSQLHelper { get; set; } 18 | 19 | /// 20 | /// 构建连接字符串 21 | /// 22 | /// 服务器地址 23 | /// 数据库 24 | /// 用户名 25 | /// 密码 26 | /// 连接字符串 27 | public abstract string BuildConnectionString(string server, string database, string userID, string password); 28 | 29 | /// 30 | /// 事务调用 31 | /// 32 | /// 方法体 33 | public void Transaction(Action action) 34 | { 35 | TransactionIsOpen.Value = true; 36 | using (TransactionScope scope = new TransactionScope()) 37 | { 38 | action(); 39 | scope.Complete(); 40 | } 41 | TransactionIsOpen.Value = false; 42 | } 43 | 44 | 45 | 46 | } 47 | 48 | 49 | } 50 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Model/Parameter.cs: -------------------------------------------------------------------------------- 1 | using System.Data; 2 | 3 | namespace HSQL.Model 4 | { 5 | public class Parameter 6 | { 7 | public Parameter(string parameterName, object value) 8 | { 9 | ParameterName = parameterName; 10 | Value = value; 11 | } 12 | 13 | public object Value { get; set; } 14 | public string ParameterName { get; set; } 15 | 16 | public byte Precision { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } 17 | public byte Scale { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } 18 | public int Size { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } 19 | public DbType DbType { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } 20 | public ParameterDirection Direction { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } 21 | 22 | public bool IsNullable => throw new System.NotImplementedException(); 23 | 24 | public string SourceColumn { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } 25 | public DataRowVersion SourceVersion { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.MySQL/MySQLConnectionPools.cs: -------------------------------------------------------------------------------- 1 | using HSQL.ConnectionPools; 2 | using MySql.Data.MySqlClient; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading; 6 | 7 | namespace HSQL.MySQL 8 | { 9 | /// 10 | /// 连接池 11 | /// 12 | internal class MySQLConnectionPools 13 | { 14 | private static int _size; 15 | private static readonly object _lockConnector = new object(); 16 | private static List _connectorList = new List(); 17 | 18 | private MySQLConnectionPools() 19 | { 20 | 21 | } 22 | 23 | internal static void Init(string connectionString, int size = 3) 24 | { 25 | _size = size; 26 | 27 | for (var i = 0; i < _size; i++) 28 | { 29 | _connectorList.Add(new Connector(new MySqlConnection(connectionString))); 30 | } 31 | } 32 | 33 | internal static IConnector GetConnector() 34 | { 35 | lock (_lockConnector) 36 | { 37 | IConnector connector = _connectorList.Where(x => x.GetState() == ConnectorState.可用).FirstOrDefault(); 38 | if (connector != null) 39 | { 40 | connector.SetState(ConnectorState.占用); 41 | return connector; 42 | } 43 | else 44 | { 45 | Thread.Sleep(1); 46 | return GetConnector(); 47 | } 48 | } 49 | } 50 | 51 | 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.MSSQLServer/SQLServerConnectionPools.cs: -------------------------------------------------------------------------------- 1 | using HSQL.ConnectionPools; 2 | using System.Collections.Generic; 3 | using System.Data.SqlClient; 4 | using System.Linq; 5 | using System.Threading; 6 | 7 | namespace HSQL.MSSQLServer 8 | { 9 | /// 10 | /// 连接池 11 | /// 12 | internal class SQLServerConnectionPools 13 | { 14 | private static int _size; 15 | private static readonly object _lockConnector = new object(); 16 | private static List _connectorList = new List(); 17 | 18 | private SQLServerConnectionPools() 19 | { 20 | 21 | } 22 | 23 | internal static void Init(string connectionString, int size = 3) 24 | { 25 | _size = size; 26 | 27 | for (var i = 0; i < _size; i++) 28 | { 29 | _connectorList.Add(new Connector(new SqlConnection(connectionString))); 30 | } 31 | } 32 | 33 | internal static IConnector GetConnector() 34 | { 35 | lock (_lockConnector) 36 | { 37 | IConnector connector = _connectorList.Where(x => x.GetState() == ConnectorState.可用).FirstOrDefault(); 38 | if (connector != null) 39 | { 40 | connector.SetState(ConnectorState.占用); 41 | return connector; 42 | } 43 | else 44 | { 45 | Thread.Sleep(1); 46 | return GetConnector(); 47 | } 48 | } 49 | } 50 | 51 | 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Base/QueryabelBase.cs: -------------------------------------------------------------------------------- 1 | using HSQL.Const; 2 | using HSQL.Model; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq.Expressions; 6 | 7 | namespace HSQL.Base 8 | { 9 | public class QueryabelBase 10 | { 11 | public QueryabelBase() 12 | { 13 | OrderInfoList = new List(); 14 | } 15 | 16 | protected IDbSQLHelper DbSQLHelper { get; set; } 17 | protected Expression> Predicate { get; set; } 18 | public List OrderInfoList { get; set; } 19 | 20 | 21 | 22 | 23 | internal void OrderBy(string field) 24 | { 25 | OrderInfoList = new List() 26 | { 27 | new OrderInfo() 28 | { 29 | By = KeywordConst.ASC, 30 | Field = field 31 | } 32 | }; 33 | } 34 | 35 | internal void OrderByDescending(string field) 36 | { 37 | OrderInfoList = new List() 38 | { 39 | new OrderInfo() 40 | { 41 | By = KeywordConst.DESC, 42 | Field = field 43 | } 44 | }; 45 | } 46 | 47 | internal void ThenOrderBy(string field) 48 | { 49 | OrderInfoList.Add(new OrderInfo() 50 | { 51 | By = KeywordConst.ASC, 52 | Field = field 53 | }); 54 | } 55 | 56 | internal void ThenOrderByDescending(string field) 57 | { 58 | OrderInfoList.Add(new OrderInfo() 59 | { 60 | By = KeywordConst.DESC, 61 | Field = field 62 | }); 63 | } 64 | 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Base/DbHelperBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data; 3 | 4 | namespace HSQL.Base 5 | { 6 | public class DbHelperBase 7 | { 8 | /// 9 | /// 是否在控制台输出Sql语句 10 | /// 11 | public bool ConsolePrintSql { get; set; } 12 | 13 | /// 14 | /// 执行增删改操作 15 | /// 16 | /// 连接对象 17 | /// 是否在控制台打印Sql语句 18 | /// 执行命令 19 | /// 参数 20 | /// 执行完成后,影响行数 21 | public int ExecuteNonQuery(IDbConnection connection, string commandText, params IDbDataParameter[] parameters) 22 | { 23 | int result = 0; 24 | using (IDbCommand command = connection.CreateCommand()) 25 | { 26 | command.CommandText = commandText; 27 | foreach (IDbDataParameter parameter in parameters) 28 | { 29 | command.Parameters.Add(parameter); 30 | } 31 | 32 | PrintSql(commandText); 33 | result = command.ExecuteNonQuery(); 34 | } 35 | return result; 36 | } 37 | 38 | /// 39 | /// 在控制台打印Sql语句 40 | /// 41 | /// 是否打印SQL语句 42 | /// 将要打印的Sql语句 43 | public void PrintSql(string commandText) 44 | { 45 | if (ConsolePrintSql) 46 | { 47 | if (!string.IsNullOrWhiteSpace(commandText)) 48 | System.Diagnostics.Trace.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} 执行的Sql语句为:{commandText}"); 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/IQueryabel.cs: -------------------------------------------------------------------------------- 1 | using HSQL.Base; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq.Expressions; 5 | 6 | namespace HSQL 7 | { 8 | public interface IQueryabel 9 | { 10 | /// 11 | /// 查询时添加 AND 条件 12 | /// 13 | /// 条件 14 | IQueryabel ConditionAnd(Expression> condition); 15 | 16 | /// 17 | /// 查询时添加 Or 条件 18 | /// 19 | /// 条件 20 | IQueryabel ConditionOr(Expression> condition); 21 | 22 | /// 23 | /// 取得符合查询条件的第一条数据 24 | /// 25 | T FirstOrDefault(); 26 | 27 | /// 28 | /// 取得符合查询条件的第一条数据,如符合条件的数据不为1条,则抛出异常 29 | /// 30 | T SingleOrDefault(); 31 | 32 | /// 33 | /// 取得符合查询条件的数据的数量 34 | /// 35 | int Count(); 36 | 37 | /// 38 | /// 检查符合查询条件的数据是否存在 39 | /// 40 | bool Exists(); 41 | 42 | /// 43 | /// 获取数据 44 | /// 45 | List ToList(); 46 | 47 | /// 48 | /// 分页获取数据 49 | /// 50 | /// 页号 51 | /// 每页记录条数 52 | List ToList(int pageIndex, int pageSize); 53 | 54 | /// 55 | /// 分页获取数据 56 | /// 57 | /// 页号 58 | /// 每页记录条数 59 | /// 总记录条数 60 | /// 总页数 61 | List ToList(int pageIndex, int pageSize, out int total, out int totalPage); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.Test/TestHelper/UnixTime.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace HSQL.Test.TestHelper 6 | { 7 | public class UnixTime 8 | { 9 | /// 10 | /// 将DateTime转换为Unix时间戳 11 | /// 说明:该Unix时间戳为 1970-1-1 08:00:00 到DateTime的秒数 12 | /// 13 | /// Unix时间戳 14 | public static long ToUnixTimeSecond(DateTime time) 15 | { 16 | var span = time - new DateTime(0x7b2, 1, 1, 8, 0, 0); 17 | return Convert.ToInt64(span.TotalSeconds); 18 | } 19 | 20 | /// 21 | /// 将Unix时间戳转换为DateTime时间 22 | /// 说明:该UnixTime时间戳应为 1970-1-1 08:00:00 到DateTime的秒数 23 | /// 24 | /// DateTime时间 25 | public static DateTime ToDateTime(long unixTime) 26 | { 27 | DateTime time2 = new DateTime(0x7b2, 1, 1, 8, 0, 0); 28 | return time2.AddSeconds(unixTime); 29 | } 30 | 31 | /// 32 | /// 将Unix时间戳转换成时间格式的字符串 33 | /// 说明:yyyy-MM-dd 34 | /// 35 | /// 时间格式的字符串 36 | public static string ToDateTimeString(long unixTime) 37 | { 38 | if (unixTime != 0) 39 | return ToDateTime(unixTime).ToString("yyyy-MM-dd"); 40 | else 41 | return string.Empty; 42 | } 43 | 44 | /// 45 | /// 将Unix时间戳转换成时间格式的字符串 46 | /// 说明:yyyy-MM-dd HH:mm:ss 47 | /// 48 | /// 时间格式的字符串 49 | public static string ToDateTimeStringHasHourMinuteSecond(long unixTime) 50 | { 51 | if (unixTime != 0) 52 | return ToDateTime(unixTime).ToString("yyyy-MM-dd HH:mm:ss"); 53 | else 54 | return string.Empty; 55 | } 56 | 57 | 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Extensions/ExpressionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | 6 | 7 | namespace HSQL 8 | { 9 | public static class ExpressionExtensions 10 | { 11 | 12 | private static Expression Compose(this Expression first, Expression second, Func merge) 13 | { 14 | Dictionary map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f); 15 | Expression secondBody = ParameterRebinder.ReplaceParameters(map, second.Body); 16 | return Expression.Lambda(merge(first.Body, secondBody), first.Parameters); 17 | } 18 | public static Expression> AndAlso(this Expression> first, Expression> second) 19 | { 20 | return first.Compose(second, Expression.AndAlso); 21 | } 22 | public static Expression> OrElse(this Expression> first, Expression> second) 23 | { 24 | return first.Compose(second, Expression.OrElse); 25 | } 26 | } 27 | 28 | class ParameterRebinder : ExpressionVisitor 29 | { 30 | private readonly Dictionary map; 31 | public ParameterRebinder(Dictionary map) 32 | { 33 | this.map = map ?? new Dictionary(); 34 | } 35 | public static Expression ReplaceParameters(Dictionary map, Expression exp) 36 | { 37 | return new ParameterRebinder(map).Visit(exp); 38 | } 39 | protected override Expression VisitParameter(ParameterExpression p) 40 | { 41 | ParameterExpression replacement; 42 | if (map.TryGetValue(p, out replacement)) 43 | { 44 | p = replacement; 45 | } 46 | return base.VisitParameter(p); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/IDbContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq.Expressions; 4 | 5 | namespace HSQL 6 | { 7 | public interface IDbContext 8 | { 9 | /// 10 | /// 执行新增操作 11 | /// 12 | /// 类型 13 | /// 要新增的实例 14 | /// 是否新增成功 15 | bool Insert(T instance); 16 | 17 | /// 18 | /// 执行更新操作 19 | /// 20 | /// 类型 21 | /// 条件表达式,可理解为 SQL 语句中的 WHERE。如:WHERE age = 16 可写为 x=> x.Age = 16 22 | /// 目标表达式,可理解为SQL 语句中的 SET。如:SET age = 16 , name = '张三' 可写为 new Student(){ Age = 16 , Name = "张三" } 23 | /// 是否更新成功 24 | bool Update(Expression> expression, T instance); 25 | 26 | /// 27 | /// 执行删除操作 28 | /// 29 | /// 类型 30 | /// 条件表达式 31 | /// 是否删除成功 32 | bool Delete(Expression> predicate); 33 | 34 | /// 35 | /// 事务调用 36 | /// 37 | /// 方法体 38 | void Transaction(Action action); 39 | 40 | /// 41 | /// 无条件查询 42 | /// 43 | /// 类型 44 | IQueryabel Query(); 45 | 46 | /// 47 | /// 无条件查询 48 | /// 49 | /// 查询条件表达式 50 | /// 类型 51 | IQueryabel Query(Expression> predicate); 52 | 53 | /// 54 | /// 使用SQL语句查询,并得到结果集 55 | /// 56 | /// SQL语句 57 | List Query(string sql); 58 | 59 | /// 60 | /// 使用SQL语句查询,并得到结果集 61 | /// 62 | /// SQL语句 63 | /// 参数 64 | List Query(string sql, dynamic parameter); 65 | 66 | /// 67 | /// 清空表 68 | /// 69 | /// 类型 70 | void TruncateTable(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Extensions/QueryabelExtensions.cs: -------------------------------------------------------------------------------- 1 | using HSQL.Base; 2 | using System; 3 | using System.Linq.Expressions; 4 | using System.Reflection; 5 | 6 | namespace HSQL 7 | { 8 | public static class QueryabelExtensions 9 | { 10 | public static IQueryabel OrderBy(this IQueryabel source, Expression> keySelector) 11 | { 12 | QueryabelBase queryabel = (QueryabelBase)source; 13 | 14 | foreach (CustomAttributeData attribute in (keySelector.Body as MemberExpression).Member.CustomAttributes) 15 | { 16 | string field = attribute.ConstructorArguments[0].Value as string; 17 | 18 | queryabel.OrderBy(field); 19 | break; 20 | } 21 | return (IQueryabel)queryabel; 22 | } 23 | 24 | public static IQueryabel OrderByDescending(this IQueryabel source, Expression> keySelector) 25 | { 26 | QueryabelBase queryabel = (QueryabelBase)source; 27 | 28 | foreach (CustomAttributeData attribute in (keySelector.Body as MemberExpression).Member.CustomAttributes) 29 | { 30 | string field = attribute.ConstructorArguments[0].Value as string; 31 | 32 | queryabel.OrderByDescending(field); 33 | break; 34 | } 35 | return (IQueryabel)queryabel; 36 | } 37 | 38 | 39 | public static IQueryabel ThenOrderBy(this IQueryabel source, Expression> keySelector) 40 | { 41 | QueryabelBase queryabel = (QueryabelBase)source; 42 | 43 | foreach (CustomAttributeData attribute in (keySelector.Body as MemberExpression).Member.CustomAttributes) 44 | { 45 | string field = attribute.ConstructorArguments[0].Value as string; 46 | 47 | queryabel.ThenOrderBy(field); 48 | break; 49 | } 50 | return (IQueryabel)queryabel; 51 | } 52 | 53 | public static IQueryabel ThenOrderByDescending(this IQueryabel source, Expression> keySelector) 54 | { 55 | QueryabelBase queryabel = (QueryabelBase)source; 56 | 57 | foreach (CustomAttributeData attribute in (keySelector.Body as MemberExpression).Member.CustomAttributes) 58 | { 59 | string field = attribute.ConstructorArguments[0].Value as string; 60 | 61 | queryabel.ThenOrderByDescending(field); 62 | break; 63 | } 64 | return (IQueryabel)queryabel; 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29609.76 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HSQL", "HSQL\HSQL.csproj", "{F022648A-6DF4-4708-B9FB-AF5D02026543}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HSQL.MySQL", "HSQL.MySQL\HSQL.MySQL.csproj", "{4D898911-9D57-4E7E-8E7F-60BE257AECA3}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HSQL.Test", "HSQL.Test\HSQL.Test.csproj", "{E6C78234-5F82-483B-A141-823004CB4EA2}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HSQL.MSSQLServer", "HSQL.MSSQLServer\HSQL.MSSQLServer.csproj", "{F494EC02-39B7-420E-A8DE-521D071F67AF}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HSQL.NugetTest", "HSQL.NugetTest\HSQL.NugetTest.csproj", "{2565FCC2-BD97-4FEE-BC2C-7249B3881436}" 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {F022648A-6DF4-4708-B9FB-AF5D02026543}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {F022648A-6DF4-4708-B9FB-AF5D02026543}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {F022648A-6DF4-4708-B9FB-AF5D02026543}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {F022648A-6DF4-4708-B9FB-AF5D02026543}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {4D898911-9D57-4E7E-8E7F-60BE257AECA3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {4D898911-9D57-4E7E-8E7F-60BE257AECA3}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {4D898911-9D57-4E7E-8E7F-60BE257AECA3}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {4D898911-9D57-4E7E-8E7F-60BE257AECA3}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {E6C78234-5F82-483B-A141-823004CB4EA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {E6C78234-5F82-483B-A141-823004CB4EA2}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {E6C78234-5F82-483B-A141-823004CB4EA2}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {E6C78234-5F82-483B-A141-823004CB4EA2}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {F494EC02-39B7-420E-A8DE-521D071F67AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {F494EC02-39B7-420E-A8DE-521D071F67AF}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {F494EC02-39B7-420E-A8DE-521D071F67AF}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {F494EC02-39B7-420E-A8DE-521D071F67AF}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {2565FCC2-BD97-4FEE-BC2C-7249B3881436}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {2565FCC2-BD97-4FEE-BC2C-7249B3881436}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {2565FCC2-BD97-4FEE-BC2C-7249B3881436}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {2565FCC2-BD97-4FEE-BC2C-7249B3881436}.Release|Any CPU.Build.0 = Release|Any CPU 42 | EndGlobalSection 43 | GlobalSection(SolutionProperties) = preSolution 44 | HideSolutionNode = FALSE 45 | EndGlobalSection 46 | GlobalSection(ExtensibilityGlobals) = postSolution 47 | SolutionGuid = {E72F8B6C-5DBF-4E1D-A442-2584ABE4A5B3} 48 | EndGlobalSection 49 | EndGlobal 50 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Factory/InstanceFactory.cs: -------------------------------------------------------------------------------- 1 | using HSQL.Base; 2 | using HSQL.Model; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Data; 6 | using System.Dynamic; 7 | using System.Linq; 8 | using System.Reflection; 9 | 10 | namespace HSQL.Factory 11 | { 12 | public class InstanceFactory 13 | { 14 | public static T CreateSingleAndDisposeReader(IDataReader reader) 15 | { 16 | T instance = default(T); 17 | var tableInfo = StoreBase.GetTableInfo(typeof(T)); 18 | try 19 | { 20 | while (reader.Read()) 21 | { 22 | instance = Create(tableInfo, reader); 23 | } 24 | } 25 | finally 26 | { 27 | if (reader != null) 28 | { 29 | if (!reader.IsClosed) 30 | { 31 | reader.Close(); 32 | } 33 | } 34 | } 35 | return instance; 36 | } 37 | 38 | public static T Create(TableInfo tableInfo, IDataReader reader) 39 | { 40 | T instance = Activator.CreateInstance(); 41 | foreach (var column in tableInfo.Columns) 42 | { 43 | object value = reader[column.Name]; 44 | if (value is DBNull) 45 | continue; 46 | 47 | column.Property.SetValue(instance, value); 48 | } 49 | return instance; 50 | } 51 | 52 | public static dynamic Create(IDataReader reader) 53 | { 54 | IDictionary expando = new ExpandoObject(); 55 | for (int i = 0; i < reader.FieldCount; i++) 56 | { 57 | var columnName = reader.GetName(i); 58 | 59 | if (expando.ContainsKey(columnName)) 60 | throw new Exception($"查询的列名{columnName}重复!"); 61 | 62 | if (reader.IsDBNull(i)) 63 | expando.Add(columnName, null); 64 | else 65 | expando.Add(columnName, reader.GetValue(i)); 66 | 67 | } 68 | return expando; 69 | } 70 | 71 | public static List CreateListAndDisposeReader(IDataReader reader) 72 | { 73 | var tableInfo = StoreBase.GetTableInfo(typeof(T)); 74 | List list = new List(); 75 | try 76 | { 77 | while (reader.Read()) 78 | { 79 | list.Add(Create(tableInfo, reader)); 80 | } 81 | } 82 | finally 83 | { 84 | if (reader != null) 85 | { 86 | if (!reader.IsClosed) 87 | { 88 | reader.Close(); 89 | } 90 | } 91 | } 92 | return list; 93 | } 94 | 95 | public static List CreateListAndDisposeReader(IDataReader reader) 96 | { 97 | List list = new List(); 98 | try 99 | { 100 | while (reader.Read()) 101 | { 102 | dynamic a = Create(reader); 103 | list.Add(a); 104 | } 105 | } 106 | finally 107 | { 108 | if (reader != null) 109 | { 110 | if (!reader.IsClosed) 111 | { 112 | reader.Close(); 113 | } 114 | } 115 | } 116 | 117 | return list; 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.Test/UnitTestTransaction.cs: -------------------------------------------------------------------------------- 1 | using HSQL.MySQL; 2 | using HSQL.Test.TestDataBaseModel; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Threading.Tasks; 7 | 8 | namespace HSQL.Test 9 | { 10 | 11 | 12 | [TestClass] 13 | public class UnitTestTransaction 14 | { 15 | //MYSQL 16 | IDbContext dbContext = new DbContext("127.0.0.1", "test", "root", "123456", 3, true); 17 | 18 | //SQLSERVER 19 | //IDbContext dbContext = new DbContext("127.0.0.1", "test", "sa", "123"); 20 | 21 | [TestMethod] 22 | public void TestTransactionInsert() 23 | { 24 | dbContext.Delete(x => x.Name.Contains("transaction_")); 25 | 26 | dbContext.Transaction(() => 27 | { 28 | var result1 = dbContext.Insert(new Student() 29 | { 30 | Id = "1", 31 | Name = "transaction_1", 32 | Age = 18, 33 | SchoolId = "123" 34 | }); 35 | var result2 = dbContext.Insert(new Student() 36 | { 37 | Id = "2", 38 | Name = "transaction_2", 39 | Age = 18, 40 | SchoolId = "123" 41 | }); 42 | }); 43 | 44 | var countYes = dbContext.Query(x => x.Name == "transaction_1" || x.Name == "transaction_2").ToList().Count; 45 | Assert.IsTrue(countYes == 2); 46 | 47 | try 48 | { 49 | dbContext.Transaction(() => 50 | { 51 | var result1 = dbContext.Insert(new Student() 52 | { 53 | Id = "3", 54 | Name = "transaction_3", 55 | Age = 18, 56 | SchoolId = "123" 57 | }); 58 | 59 | throw new Exception("asdf"); 60 | 61 | var result2 = dbContext.Insert(new Student() 62 | { 63 | Id = "4", 64 | Name = "transaction_4", 65 | Age = 18, 66 | SchoolId = "123" 67 | }); 68 | }); 69 | } 70 | catch (Exception ex) 71 | { 72 | 73 | } 74 | 75 | var countNo = dbContext.Query(x => x.Name == "transaction_1" || x.Name == "transaction_2" || x.Name == "transaction_3" || x.Name == "transaction_4").ToList().Count; 76 | Assert.IsTrue(countNo == 2); 77 | } 78 | 79 | 80 | [TestMethod] 81 | public void TestTransactionManyTask() 82 | { 83 | 84 | dbContext.Delete(x => x.Name.Contains("TransactionManyTask_")); 85 | 86 | List list = new List(); 87 | for (var i = 0; i < 50; i++) 88 | { 89 | var taskIndex = i; 90 | var task = new Task(() => 91 | { 92 | dbContext.Transaction(() => 93 | { 94 | for (var j = 0; j < 10; j++) 95 | { 96 | dbContext.Insert(new Student() 97 | { 98 | Id = Guid.NewGuid().ToString(), 99 | Name = $"TransactionManyTask_{taskIndex}_{j}", 100 | Age = 18, 101 | SchoolId = "123" 102 | }); 103 | } 104 | }); 105 | }); 106 | list.Add(task); 107 | } 108 | 109 | list.ForEach(x => 110 | { 111 | x.Start(); 112 | }); 113 | 114 | Task.WaitAll(list.ToArray()); 115 | var count = dbContext.Query(x => x.Name.Contains("TransactionManyTask_")).ToList().Count; 116 | Assert.IsTrue(500 == count); 117 | } 118 | 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.MySQL/MySQLHelper.cs: -------------------------------------------------------------------------------- 1 | using HSQL.Base; 2 | using HSQL.ConnectionPools; 3 | using HSQL.Factory; 4 | using HSQL.Model; 5 | using MySql.Data.MySqlClient; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Data; 9 | using System.Linq; 10 | 11 | namespace HSQL.MySQL 12 | { 13 | internal class MySQLHelper : DbHelperBase, IDbSQLHelper 14 | { 15 | private string ConnectionString { get; set; } 16 | public MySQLHelper(string connectionString, bool consolePrintSql) 17 | { 18 | ConnectionString = connectionString; 19 | ConsolePrintSql = consolePrintSql; 20 | } 21 | 22 | public int ExecuteNonQuery(bool isNewConnection, string commandText, params IDbDataParameter[] parameters) 23 | { 24 | if (string.IsNullOrWhiteSpace(commandText)) 25 | throw new ArgumentNullException("执行命令不能为空"); 26 | 27 | int result = 0; 28 | if (isNewConnection == true) 29 | { 30 | using (IDbConnection connection = new MySqlConnection(ConnectionString)) 31 | { 32 | connection.Open(); 33 | result = ExecuteNonQuery(connection, commandText, parameters); 34 | } 35 | } 36 | else 37 | { 38 | using (IConnector connector = MySQLConnectionPools.GetConnector()) 39 | { 40 | result = ExecuteNonQuery(connector.GetConnection(), commandText, parameters); 41 | } 42 | } 43 | return result; 44 | } 45 | 46 | public object ExecuteScalar(string commandText, params IDbDataParameter[] parameters) 47 | { 48 | if (string.IsNullOrWhiteSpace(commandText)) 49 | throw new ArgumentNullException("执行命令不能为空"); 50 | 51 | object result = null; 52 | using (IConnector connector = MySQLConnectionPools.GetConnector()) 53 | { 54 | using (IDbCommand command = connector.GetConnection().CreateCommand()) 55 | { 56 | command.CommandText = commandText; 57 | foreach (IDbDataParameter parameter in parameters) 58 | { 59 | command.Parameters.Add(parameter); 60 | } 61 | PrintSql(commandText); 62 | result = command.ExecuteScalar(); 63 | } 64 | } 65 | return result; 66 | } 67 | 68 | public List ExecuteList(string commandText, params IDbDataParameter[] parameters) 69 | { 70 | if (string.IsNullOrWhiteSpace(commandText)) 71 | throw new ArgumentNullException("执行命令不能为空"); 72 | 73 | List list = new List(); 74 | using (IConnector connector = MySQLConnectionPools.GetConnector()) 75 | { 76 | IDbCommand command = connector.GetConnection().CreateCommand(); 77 | command.CommandText = commandText; 78 | foreach (IDbDataParameter parameter in parameters) 79 | { 80 | command.Parameters.Add(parameter); 81 | } 82 | PrintSql(commandText); 83 | IDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection); 84 | list = InstanceFactory.CreateListAndDisposeReader(reader); 85 | } 86 | return list; 87 | } 88 | 89 | public List ExecuteList(string commandText, params IDbDataParameter[] parameters) 90 | { 91 | if (string.IsNullOrWhiteSpace(commandText)) 92 | throw new ArgumentNullException("执行命令不能为空"); 93 | 94 | List list = new List(); 95 | using (IConnector connector = MySQLConnectionPools.GetConnector()) 96 | { 97 | IDbCommand command = connector.GetConnection().CreateCommand(); 98 | command.CommandText = commandText; 99 | foreach (IDbDataParameter parameter in parameters) 100 | { 101 | command.Parameters.Add(parameter); 102 | } 103 | PrintSql(commandText); 104 | IDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection); 105 | list = InstanceFactory.CreateListAndDisposeReader(reader); 106 | } 107 | return list; 108 | } 109 | 110 | 111 | public IDbDataParameter[] Convert(List parameters) 112 | { 113 | return parameters.Select(x => new MySqlParameter(x.ParameterName, x.Value)).ToArray(); 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.MSSQLServer/SQLServerHelper.cs: -------------------------------------------------------------------------------- 1 | using HSQL.Base; 2 | using HSQL.ConnectionPools; 3 | using HSQL.Factory; 4 | using HSQL.Model; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Data; 8 | using System.Data.SqlClient; 9 | using System.Linq; 10 | using System.Reflection; 11 | 12 | namespace HSQL.MSSQLServer 13 | { 14 | internal class SQLServerHelper : DbHelperBase, IDbSQLHelper 15 | { 16 | 17 | private string ConnectionString { get; set; } 18 | public SQLServerHelper(string connectionString, bool consolePrintSql) 19 | { 20 | ConnectionString = connectionString; 21 | ConsolePrintSql = consolePrintSql; 22 | } 23 | 24 | public int ExecuteNonQuery(bool isNewConnection, string commandText, params IDbDataParameter[] parameters) 25 | { 26 | if (string.IsNullOrWhiteSpace(commandText)) 27 | throw new ArgumentNullException("执行命令不能为空"); 28 | 29 | int result = 0; 30 | if (isNewConnection == true) 31 | { 32 | using (IDbConnection connection = new SqlConnection(ConnectionString)) 33 | { 34 | connection.Open(); 35 | result = ExecuteNonQuery(connection, commandText, parameters); 36 | } 37 | } 38 | else 39 | { 40 | using (IConnector connector = SQLServerConnectionPools.GetConnector()) 41 | { 42 | result = ExecuteNonQuery(connector.GetConnection(), commandText, parameters); 43 | } 44 | } 45 | return result; 46 | } 47 | 48 | public object ExecuteScalar(string commandText, params IDbDataParameter[] parameters) 49 | { 50 | if (string.IsNullOrWhiteSpace(commandText)) 51 | throw new ArgumentNullException("执行命令不能为空"); 52 | 53 | object result = null; 54 | using (IConnector connector = SQLServerConnectionPools.GetConnector()) 55 | { 56 | using (IDbCommand command = connector.GetConnection().CreateCommand()) 57 | { 58 | command.CommandText = commandText; 59 | foreach (IDbDataParameter parameter in parameters) 60 | { 61 | command.Parameters.Add(parameter); 62 | } 63 | PrintSql(commandText); 64 | result = command.ExecuteScalar(); 65 | } 66 | } 67 | return result; 68 | } 69 | 70 | public List ExecuteList(string commandText, params IDbDataParameter[] parameters) 71 | { 72 | if (string.IsNullOrWhiteSpace(commandText)) 73 | throw new ArgumentNullException("执行命令不能为空"); 74 | 75 | List list = new List(); 76 | using (IConnector connector = SQLServerConnectionPools.GetConnector()) 77 | { 78 | IDbCommand command = connector.GetConnection().CreateCommand(); 79 | command.CommandText = commandText; 80 | foreach (IDbDataParameter parameter in parameters) 81 | { 82 | command.Parameters.Add(parameter); 83 | } 84 | PrintSql(commandText); 85 | IDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection); 86 | list = InstanceFactory.CreateListAndDisposeReader(reader); 87 | } 88 | return list; 89 | } 90 | 91 | public List ExecuteList(string commandText, params IDbDataParameter[] parameters) 92 | { 93 | if (string.IsNullOrWhiteSpace(commandText)) 94 | throw new ArgumentNullException("执行命令不能为空"); 95 | 96 | List list = new List(); 97 | using (IConnector connector = SQLServerConnectionPools.GetConnector()) 98 | { 99 | IDbCommand command = connector.GetConnection().CreateCommand(); 100 | command.CommandText = commandText; 101 | foreach (IDbDataParameter parameter in parameters) 102 | { 103 | command.Parameters.Add(parameter); 104 | } 105 | PrintSql(commandText); 106 | IDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection); 107 | list = InstanceFactory.CreateListAndDisposeReader(reader); 108 | } 109 | return list; 110 | } 111 | 112 | public IDbDataParameter[] Convert(List parameters) 113 | { 114 | return parameters.Select(x => new SqlParameter(x.ParameterName, x.Value)).ToArray(); 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.MySQL/DbContext.cs: -------------------------------------------------------------------------------- 1 | using HSQL.Base; 2 | using HSQL.Exceptions; 3 | using HSQL.Factory; 4 | using HSQL.Model; 5 | using MySql.Data.MySqlClient; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Linq.Expressions; 9 | 10 | namespace HSQL.MySQL 11 | { 12 | public class DbContext : DbContextBase, IDbContext 13 | { 14 | /// 15 | /// 构建数据库对象 16 | /// 17 | /// 服务器地址 18 | /// 数据库名称 19 | /// 用户名 20 | /// 密码 21 | /// 连接池连接数 22 | /// 是否在控制台输出Sql语句 23 | public DbContext(string server, string database, string userId, string password, int poolSize = 3, bool consolePrintSql = false) 24 | { 25 | if (string.IsNullOrWhiteSpace(server) 26 | || string.IsNullOrWhiteSpace(database) 27 | || string.IsNullOrWhiteSpace(userId) 28 | || string.IsNullOrWhiteSpace(password)) 29 | throw new ConnectionStringIsEmptyException(); 30 | 31 | if (poolSize <= 0) 32 | throw new ConnectionStringIsEmptyException($"连接数最小为一个!"); 33 | 34 | string connectionString = BuildConnectionString(server, database, userId, password); 35 | MySQLConnectionPools.Init(connectionString, poolSize); 36 | DbSQLHelper = new MySQLHelper(connectionString, consolePrintSql); 37 | } 38 | 39 | public override string BuildConnectionString(string server, string database, string userID, string password) 40 | { 41 | MySqlConnectionStringBuilder connectionStringBuilder = new MySqlConnectionStringBuilder() 42 | { 43 | Server = server, 44 | Database = database, 45 | UserID = userID, 46 | Password = password 47 | }; 48 | return connectionStringBuilder.ToString(); 49 | } 50 | 51 | public bool Insert(T instance) 52 | { 53 | if (instance == null) 54 | throw new DataIsNullException(); 55 | 56 | string sql = StoreBase.BuildInsertSQL(instance); 57 | var parameters = StoreBase.BuildParameters(ExpressionFactory.GetColumnList(instance)); 58 | 59 | bool isNewConnection = TransactionIsOpen.Value; 60 | return DbSQLHelper.ExecuteNonQuery(isNewConnection, sql, DbSQLHelper.Convert(parameters)) > 0; 61 | } 62 | 63 | public bool Update(Expression> expression, T instance) 64 | { 65 | if (expression == null) 66 | throw new ExpressionIsNullException(); 67 | if (instance == null) 68 | throw new DataIsNullException(); 69 | 70 | var result = StoreBase.BuildUpdateSQLAndParameters(expression, instance); 71 | 72 | bool isNewConnection = TransactionIsOpen.Value; 73 | return DbSQLHelper.ExecuteNonQuery(isNewConnection, result.Item1, DbSQLHelper.Convert(result.Item2)) > 0; 74 | } 75 | 76 | public bool Delete(Expression> predicate) 77 | { 78 | if (predicate == null) 79 | throw new ExpressionIsNullException(); 80 | 81 | Sql sql = StoreBase.BuildDeleteSQL(predicate); 82 | 83 | bool isNewConnection = TransactionIsOpen.Value; 84 | return DbSQLHelper.ExecuteNonQuery(isNewConnection, sql.CommandText, DbSQLHelper.Convert(sql.Parameters)) > 0; 85 | } 86 | 87 | public IQueryabel Query() 88 | { 89 | return Query(null); 90 | } 91 | 92 | public IQueryabel Query(Expression> predicate) 93 | { 94 | IQueryabel queryabel = new MySQLQueryabel(DbSQLHelper, predicate); 95 | return queryabel; 96 | } 97 | 98 | public List Query(string sql) 99 | { 100 | if (string.IsNullOrWhiteSpace(sql)) 101 | throw new EmptySQLException(); 102 | 103 | List list = DbSQLHelper.ExecuteList(sql); 104 | return list; 105 | } 106 | 107 | public List Query(string sql, dynamic parameter) 108 | { 109 | if (string.IsNullOrWhiteSpace(sql)) 110 | throw new EmptySQLException(); 111 | 112 | var parameters = StoreBase.DynamicToParameters(parameter); 113 | List list = DbSQLHelper.ExecuteList(sql, DbSQLHelper.Convert(parameters)); 114 | return list; 115 | } 116 | 117 | public void TruncateTable() 118 | { 119 | var tableInfo = StoreBase.GetTableInfo(typeof(T)); 120 | DbSQLHelper.ExecuteNonQuery(true, $"TRUNCATE TABLE {tableInfo.Name};"); 121 | } 122 | } 123 | 124 | 125 | } 126 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.MSSQLServer/DbContext.cs: -------------------------------------------------------------------------------- 1 | using HSQL.Base; 2 | using HSQL.Exceptions; 3 | using HSQL.Factory; 4 | using HSQL.Model; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Data.SqlClient; 8 | using System.Linq.Expressions; 9 | 10 | namespace HSQL.MSSQLServer 11 | { 12 | public class DbContext : DbContextBase, IDbContext 13 | { 14 | /// 15 | /// 构建数据库对象 16 | /// 17 | /// 服务器地址 18 | /// 数据库名称 19 | /// 用户名 20 | /// 密码 21 | /// 连接池连接数 22 | /// 是否在控制台输出Sql语句 23 | public DbContext(string server, string database, string userId, string password, int poolSize = 3, bool consolePrintSql = false) 24 | { 25 | if (string.IsNullOrWhiteSpace(server) 26 | || string.IsNullOrWhiteSpace(database) 27 | || string.IsNullOrWhiteSpace(userId) 28 | || string.IsNullOrWhiteSpace(password)) 29 | throw new ConnectionStringIsEmptyException(); 30 | 31 | if (poolSize <= 0) 32 | throw new ConnectionStringIsEmptyException($"连接数最小为一个!"); 33 | 34 | string connectionString = BuildConnectionString(server, database, userId, password); 35 | SQLServerConnectionPools.Init(connectionString, poolSize); 36 | DbSQLHelper = new SQLServerHelper(connectionString, consolePrintSql); 37 | } 38 | 39 | public override string BuildConnectionString(string server, string database, string userID, string password) 40 | { 41 | SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder() 42 | { 43 | DataSource = server, 44 | InitialCatalog = database, 45 | UserID = userID, 46 | Password = password 47 | }; 48 | return connectionStringBuilder.ToString(); 49 | } 50 | 51 | 52 | 53 | public bool Insert(T instance) 54 | { 55 | if (instance == null) 56 | throw new DataIsNullException(); 57 | 58 | string sql = StoreBase.BuildInsertSQL(instance); 59 | var parameters = StoreBase.BuildParameters(ExpressionFactory.GetColumnList(instance)); 60 | 61 | bool isNewConnection = TransactionIsOpen.Value; 62 | return DbSQLHelper.ExecuteNonQuery(isNewConnection, sql, DbSQLHelper.Convert(parameters)) > 0; 63 | } 64 | 65 | public bool Update(Expression> expression, T instance) 66 | { 67 | if (expression == null) 68 | throw new ExpressionIsNullException(); 69 | if (instance == null) 70 | throw new DataIsNullException(); 71 | 72 | Tuple> result = StoreBase.BuildUpdateSQLAndParameters(expression, instance); 73 | 74 | bool isNewConnection = TransactionIsOpen.Value; 75 | return DbSQLHelper.ExecuteNonQuery(isNewConnection, result.Item1, DbSQLHelper.Convert(result.Item2)) > 0; 76 | } 77 | 78 | public bool Delete(Expression> predicate) 79 | { 80 | if (predicate == null) 81 | throw new ExpressionIsNullException(); 82 | 83 | Sql sql = StoreBase.BuildDeleteSQL(predicate); 84 | 85 | bool isNewConnection = TransactionIsOpen.Value; 86 | return DbSQLHelper.ExecuteNonQuery(isNewConnection, sql.CommandText, DbSQLHelper.Convert(sql.Parameters)) > 0; 87 | } 88 | 89 | public IQueryabel Query() 90 | { 91 | return Query(null); 92 | } 93 | 94 | public IQueryabel Query(Expression> predicate) 95 | { 96 | IQueryabel queryabel = new SQLServerQueryabel(DbSQLHelper, predicate); 97 | return queryabel; 98 | } 99 | 100 | public List Query(string sql) 101 | { 102 | if (string.IsNullOrWhiteSpace(sql)) 103 | throw new EmptySQLException(); 104 | 105 | List list = DbSQLHelper.ExecuteList(sql); 106 | return list; 107 | } 108 | 109 | public List Query(string sql, dynamic parameter) 110 | { 111 | if (string.IsNullOrWhiteSpace(sql)) 112 | throw new EmptySQLException(); 113 | 114 | var parameters = StoreBase.DynamicToParameters(parameter); 115 | 116 | List list = DbSQLHelper.ExecuteList(sql, DbSQLHelper.Convert(parameters)); 117 | return list; 118 | } 119 | 120 | public void TruncateTable() 121 | { 122 | var tableInfo = StoreBase.GetTableInfo(typeof(T)); 123 | DbSQLHelper.ExecuteNonQuery(true, $"TRUNCATE TABLE {tableInfo.Name};"); 124 | } 125 | } 126 | 127 | 128 | } 129 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 欢迎使用 ORM框架 HSQL 2 | 3 | **HSQL 是一种轻量级的基于 .NET 的数据库对象关系映射「ORM」框架** 4 | 5 | ![markdown](https://github.com/hexu6788/HSQL/blob/master/file/logo-2.png?raw=true "HSQL") 6 | 7 | HSQL 是一种可以使用非常`简单`且`高效`的方式进行数据库操作的一种框架,通过简单的语法,使数据库操作不再成为难事。目前支持的数据库有 MySql、SQLServer。 8 | 9 | ### 安装方法 10 | MySQL 11 | ```csharp 12 | Install-Package HSQL.MySQL -Version 1.0.0.16 13 | ``` 14 | MSSQLServer 15 | ```csharp 16 | Install-Package HSQL.MSSQLServer -Version 1.0.0.16 17 | ``` 18 | 19 | ### 使用方法 20 | + 创建映射模型 21 | + 创建数据库操作实例 22 | + 进行数据库操作 23 | + 新增 24 | + 修改 25 | + 删除 26 | + 查询 27 | + 单实例查询 28 | + 分页查询 29 | + 灵活条件查询 30 | + SQL语句方式查询 31 | + 事务 32 | 33 | 34 | 创建映射模型: 35 | ```csharp 36 | [Table("t_student")] 37 | public class Student 38 | { 39 | [Column("id")] 40 | public string Id { get; set; } 41 | 42 | [Column("name")] 43 | public string Name { get; set; } 44 | 45 | [Column("age")] 46 | public int Age { get; set; } 47 | 48 | [Column("school_id")] 49 | public string SchoolId { get; set; } 50 | 51 | [Column("birthday")] 52 | public long Birthday { get; set; } 53 | } 54 | ``` 55 | Table 标记一个表对象。如:[Table("t_student")] 代表 Student 类将映射为数据库表 t_student
Column 标记一个列对象。如:[Column("id")] 代表 Id 属性将映射为数据库列 id 56 | 57 | 58 | 59 | 60 | 创建数据库操作实例: 61 | 62 | > 参数方式创建,可设置连接池,默认开启连接池,连接池默认数量为3 63 | ```csharp 64 | IDbContext dbContext = new DbContext("127.0.0.1", "test", "root", "123456"); 65 | ``` 66 | 67 | 新增: 68 | ```csharp 69 | var result = dbContext.Insert(new Student() 70 | { 71 | Name = "zhangsan", 72 | Age = 18, 73 | SchoolId = "123" 74 | }); 75 | ``` 76 | > Insert 方法可插入一个对象,表示对 t_student 表插入一条数据。
最后被解释为 SQL 语句 ->
INSERT INTO t_student(id,name,age,school_id,birthday) VALUES(@id,@name,@age,@school_id,@birthday); 77 | 78 | 79 | 80 | 81 | 修改: 82 | ```csharp 83 | var result = dbContext.Update(x => x.Id.Contains("test_update_list"), new Student() { Age = 19 }); 84 | ``` 85 | > Update 方法表示更新操作。如:
参数1:x => x.Id.Contains("test_update_list") 被解释为 WHERE id LIKE '%test_update_list%'
参数2:new Student() { Age = 19 } 被解释为 SET age = @age
最终SQL语句为:
UPDATE t_student SET age = @age WHERE id LIKE '%test_update_list%'; 86 | 87 | 88 | 89 | 90 | 91 | 删除: 92 | ```csharp 93 | var result = dbContext.Delete(x => x.Age > 0); 94 | ``` 95 | > Delete 方法表示删除操作。最终被解释为 SQL 语句:
DELETE FROM t_student WHERE age > 0; 96 | 97 | 98 | 99 | 100 | 查询: 101 | ```csharp 102 | var list = dbContext.Query(x => x.Age == 19 103 | && x.Id.Contains("test_query_list")) 104 | .ToList(); 105 | ``` 106 | > Query => ToList 方法表示查询操作。最终被解释为 SQL 语句:
SELECT id,name,age,school_id,birthday FROM t_student WHERE age = 19 AND id LIKE '%test_query_list%'; 107 | 108 | 109 | 110 | 111 | 单实例查询: 112 | ```csharp 113 | var student = dbContext.Query(x => x.Age == 19 114 | && x.Id.Equals("test_query_single")) 115 | .FirstOrDefault(); 116 | ``` 117 | > Query => ToList 方法表示查询操作:
当 Dialect 为 MySQL 时 最终被解释为 SQL 语句:
SELECT id,name,age,school_id,birthday FROM t_student WHERE age = 19 AND id = 'test_query_single' LIMIT 0,1;
当 Dialect 为 SQLServer 时 最终被解释为 SQL 语句:
SELECT TOP 1 id,name,age,school_id,birthday FROM t_student WITH(NOLOCK) WHERE age = 19 AND id = 'test_query_single'; 118 | 119 | 120 | 121 | 122 | 分页查询: 123 | ```csharp 124 | var list = dbContext.Query(x => x.Age == 19 125 | && x.Id.Contains("test_query_page_list")) 126 | .ToList(2, 10); 127 | ``` 128 | > Query => ToList(2,10) 方法表示分页查询操作,pageIndex 为第几页,pageSize 为每页记录条数。
最终被解释为 SQL 语句:
SELECT id,name,age,school_id,birthday FROM t_student WHERE age = 19 AND id LIKE '%test_query_page_list%' LIMIT 10,10; 129 | 130 | 131 | 132 | 133 | 灵活条件查询: 134 | ```csharp 135 | var list = dbContext.Query(x => x.Age == 19 136 | && x.Id.Contains("test_query_page_list")) 137 | .ConditionAnd(x => x.Name == "zhangsan") 138 | .ToList(2, 10); 139 | ``` 140 | > ConditionAnd 方法可以对查询进行动态增加条件。
最终解释的 SQL 的 WHERE 部分会包含 AND name = 'zhangsan' 141 | 142 | SQL语句方式查询: 143 | ```csharp 144 | var list = dbContext.Query("SELECT t.id,t.name,s.id AS school_id 145 | FROM t_student AS t 146 | LEFT JOIN t_school AS s ON t.school_id = s.id 147 | WHERE t.id = @id AND t.age > @age;", 148 | new 149 | { 150 | id = "test_query_list", 151 | age = 1 152 | }); 153 | ``` 154 | > SQL语句方式查询,如有查询SQL有参数,则需使用参数化查询才能防止SQL注入攻击 155 | 156 | 事务: 157 | ```csharp 158 | var stu1 = new Student() 159 | { 160 | Id = "1", 161 | Name = "zhangsan", 162 | Age = 18, 163 | SchoolId = "123" 164 | }; 165 | dbContext.Transaction(() => 166 | { 167 | var result1 = dbContext.Insert(stu1); 168 | var result2 = dbContext.Update(x=> x.Id == "2", new Student() 169 | { 170 | Name = "zhangsan", 171 | Age = 18, 172 | SchoolId = "123" 173 | }); 174 | }); 175 | ``` 176 | > Transaction 方法可以进行事务操作,当方法中 throw 任意异常,事务将回滚。否则当方法执行完后事务会提交 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /code/HSQL/HSQL/Base/StoreBase.cs: -------------------------------------------------------------------------------- 1 | using HSQL.Attribute; 2 | using HSQL.Const; 3 | using HSQL.Exceptions; 4 | using HSQL.Factory; 5 | using HSQL.Model; 6 | using System; 7 | using System.Collections.Concurrent; 8 | using System.Collections.Generic; 9 | using System.Linq; 10 | using System.Linq.Expressions; 11 | using System.Reflection; 12 | 13 | namespace HSQL.Base 14 | { 15 | public class StoreBase 16 | { 17 | private static ConcurrentDictionary _tableInfoStore = new ConcurrentDictionary(); 18 | private static ConcurrentDictionary _memberAttributeNameStore = new ConcurrentDictionary(); 19 | 20 | public static TableInfo GetTableInfo(Type type) 21 | { 22 | TableInfo tableInfo; 23 | if (_tableInfoStore.ContainsKey(type)) 24 | { 25 | bool tryGetValue = _tableInfoStore.TryGetValue(type, out tableInfo); 26 | if (tryGetValue) 27 | return tableInfo; 28 | } 29 | 30 | var columns = new List(); 31 | foreach (PropertyInfo property in type.GetProperties()) 32 | { 33 | foreach (var attribute in property.GetCustomAttributes(true)) 34 | { 35 | if (attribute is ColumnAttribute) 36 | { 37 | columns.Add(new ColumnInfo() 38 | { 39 | Identity = attribute is IdentityAttribute ? true : false, 40 | Name = ((ColumnAttribute)attribute).Name, 41 | Property = property 42 | }); 43 | } 44 | } 45 | } 46 | 47 | tableInfo = new TableInfo() 48 | { 49 | Name = ((TableAttribute)type.GetCustomAttributes(TypeOfConst.TableAttribute, true)[0]).Name, 50 | DefaultOrderColumnName = columns[0].Name, 51 | Columns = columns, 52 | ColumnsComma = string.Join(",", columns.Select(column => column.Name)) 53 | }; 54 | _tableInfoStore.TryAdd(type, tableInfo); 55 | return tableInfo; 56 | } 57 | 58 | 59 | 60 | internal static string GetColumnName(MemberExpression expression) 61 | { 62 | var columnName = string.Empty; 63 | if (_memberAttributeNameStore.ContainsKey(expression.Member)) 64 | { 65 | bool tryGetValue = _memberAttributeNameStore.TryGetValue(expression.Member, out columnName); 66 | if (tryGetValue) 67 | return columnName; 68 | } 69 | 70 | columnName = ((ColumnAttribute)expression.Member.GetCustomAttributes(TypeOfConst.ColumnAttribute, true)[0]).Name; 71 | _memberAttributeNameStore.TryAdd(expression.Member, columnName); 72 | return columnName; 73 | } 74 | 75 | public static string BuildInsertSQL(T instance) 76 | { 77 | var tableInfo = GetTableInfo(instance.GetType()); 78 | var columnNameList = tableInfo.Columns.Where(column => column.Identity == false).Select(column => column.Name).ToList(); 79 | return $"INSERT INTO {tableInfo.Name}({string.Join(",", columnNameList)}) VALUES({string.Join(",", columnNameList.Select(columnName => $"@{columnName}"))});"; 80 | } 81 | 82 | public static Sql BuildDeleteSQL(Expression> predicate) 83 | { 84 | if (predicate == null) 85 | throw new ExpressionIsNullException(); 86 | 87 | var tableInfo = GetTableInfo(typeof(T)); 88 | Sql sql = ExpressionFactory.ToWhereSql(predicate); 89 | sql.CommandText = $"DELETE FROM {tableInfo.Name} WHERE {sql.CommandText};"; 90 | return sql; 91 | } 92 | 93 | public static string BuildOrderSQL(List orderInfoList) 94 | { 95 | if (orderInfoList.Count <= 0) 96 | return string.Empty; 97 | 98 | return $" ORDER BY {string.Join(", ", orderInfoList.Select(order => $"{order.Field} {order.By}"))}"; 99 | } 100 | 101 | public static List BuildParameters(List columnList) 102 | { 103 | return columnList.Select(x => new Parameter(x.Name, x.Value)).ToList(); 104 | } 105 | 106 | public static List DynamicToParameters(object parameters) 107 | { 108 | if (parameters == null) 109 | throw new EmptyParameterException(); 110 | 111 | PropertyInfo[] properties = parameters.GetType().GetProperties(); 112 | 113 | return properties.Select(property => new Parameter(string.Format("@{0}", property.Name), property.GetValue(parameters, null))).ToList(); 114 | } 115 | 116 | public static Tuple> BuildUpdateSQLAndParameters(Expression> expression, T instance) 117 | { 118 | Sql sql = ExpressionFactory.ToWhereSql(expression); 119 | 120 | List columnList = ExpressionFactory.GetColumnListWithOutNull(instance); 121 | 122 | var tableInfo = GetTableInfo(instance.GetType()); 123 | string commandText = $"UPDATE {tableInfo.Name} SET {string.Join(" , ", columnList.Select(x => string.Format("{0} = @{1}", x.Name, x.Name)))} WHERE {sql.CommandText};"; 124 | 125 | var parameters = BuildParameters(columnList); 126 | parameters.AddRange(sql.Parameters); 127 | return new Tuple>(commandText, parameters); 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.MySQL/MySQLQueryabel.cs: -------------------------------------------------------------------------------- 1 | using HSQL.Base; 2 | using HSQL.Exceptions; 3 | using HSQL.Factory; 4 | using HSQL.Model; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Linq.Expressions; 9 | using System.Text; 10 | 11 | namespace HSQL.MySQL 12 | { 13 | public class MySQLQueryabel : QueryabelBase, IQueryabel 14 | { 15 | public MySQLQueryabel(IDbSQLHelper dbSQLHelper, Expression> predicate) 16 | { 17 | DbSQLHelper = dbSQLHelper; 18 | Predicate = predicate; 19 | } 20 | 21 | public IQueryabel ConditionAnd(Expression> condition) 22 | { 23 | if (Predicate == null) 24 | Predicate = condition; 25 | else 26 | Predicate = Predicate.AndAlso(condition); 27 | 28 | return this; 29 | } 30 | 31 | public IQueryabel ConditionOr(Expression> condition) 32 | { 33 | if (Predicate == null) 34 | Predicate = condition; 35 | else 36 | Predicate = Predicate.OrElse(condition); 37 | 38 | return this; 39 | } 40 | 41 | public int Count() 42 | { 43 | var tableInfo = StoreBase.GetTableInfo(typeof(T)); 44 | var sql = ExpressionFactory.ToWhereSql(Predicate); 45 | var builder = new StringBuilder($"SELECT COUNT(*) FROM {tableInfo.Name}"); 46 | if (!string.IsNullOrWhiteSpace(sql.CommandText)) 47 | builder.Append($" WHERE {sql.CommandText}"); 48 | 49 | var parameters = DbSQLHelper.Convert(sql.Parameters); 50 | 51 | int total = Convert.ToInt32(DbSQLHelper.ExecuteScalar(builder.ToString(), parameters)); 52 | return total; 53 | } 54 | 55 | public bool Exists() 56 | { 57 | return Count() > 0; 58 | } 59 | 60 | public List ToList() 61 | { 62 | var tableInfo = StoreBase.GetTableInfo(typeof(T)); 63 | var sql = ExpressionFactory.ToWhereSql(Predicate); 64 | 65 | var builder = new StringBuilder(); 66 | builder.Append($"SELECT {tableInfo.ColumnsComma} FROM {tableInfo.Name}"); 67 | if (!string.IsNullOrWhiteSpace(sql.CommandText)) 68 | builder.Append($" WHERE {sql.CommandText}"); 69 | 70 | if (OrderInfoList.Count > 0) 71 | builder.Append(StoreBase.BuildOrderSQL(OrderInfoList)); 72 | 73 | var parameters = DbSQLHelper.Convert(sql.Parameters); 74 | 75 | List list = DbSQLHelper.ExecuteList(builder.ToString(), parameters); 76 | return list; 77 | } 78 | 79 | public List ToList(int pageIndex, int pageSize) 80 | { 81 | var tableInfo = StoreBase.GetTableInfo(typeof(T)); 82 | var pageStart = (pageIndex - 1) * pageSize; 83 | var sql = ExpressionFactory.ToWhereSql(Predicate); 84 | 85 | var builder = new StringBuilder(); 86 | builder.Append($"SELECT {tableInfo.ColumnsComma} FROM {tableInfo.Name}"); 87 | if (!string.IsNullOrWhiteSpace(sql.CommandText)) 88 | builder.Append($" WHERE {sql.CommandText}"); 89 | if (OrderInfoList.Count > 0) 90 | builder.Append(StoreBase.BuildOrderSQL(OrderInfoList)); 91 | builder.Append($" LIMIT {pageStart},{pageSize}"); 92 | 93 | var parameters = DbSQLHelper.Convert(sql.Parameters); 94 | 95 | List list = DbSQLHelper.ExecuteList(builder.ToString(), parameters); 96 | return list; 97 | } 98 | 99 | public List ToList(int pageIndex, int pageSize, out int total, out int totalPage) 100 | { 101 | var tableInfo = StoreBase.GetTableInfo(typeof(T)); 102 | var sql = ExpressionFactory.ToWhereSql(Predicate); 103 | var pageStart = (pageIndex - 1) * pageSize; 104 | 105 | var sqlBuilder = new StringBuilder($"SELECT {tableInfo.ColumnsComma} FROM {tableInfo.Name}"); 106 | var pageBuilder = new StringBuilder($"SELECT COUNT(*) FROM {tableInfo.Name}"); 107 | if (!string.IsNullOrWhiteSpace(sql.CommandText)) 108 | { 109 | sqlBuilder.Append($" WHERE {sql.CommandText}"); 110 | pageBuilder.Append($" WHERE {sql.CommandText}"); 111 | } 112 | 113 | var parameters = DbSQLHelper.Convert(sql.Parameters); 114 | total = Convert.ToInt32(DbSQLHelper.ExecuteScalar(pageBuilder.ToString(), parameters)); 115 | totalPage = (total % pageSize == 0) ? (total / pageSize) : (total / pageSize + 1); 116 | 117 | if (OrderInfoList.Count > 0) 118 | sqlBuilder.Append(StoreBase.BuildOrderSQL(OrderInfoList)); 119 | 120 | sqlBuilder.Append($" LIMIT {pageStart},{pageSize}"); 121 | 122 | List list = DbSQLHelper.ExecuteList(sqlBuilder.ToString(), parameters); 123 | return list; 124 | } 125 | 126 | public T SingleOrDefault() 127 | { 128 | var tableInfo = StoreBase.GetTableInfo(typeof(T)); 129 | var sql = ExpressionFactory.ToWhereSql(Predicate); 130 | 131 | var sqlBuilder = new StringBuilder($"SELECT {tableInfo.ColumnsComma} FROM {tableInfo.Name}"); 132 | var pageBuilder = new StringBuilder($"SELECT COUNT(*) FROM {tableInfo.Name}"); 133 | if (!string.IsNullOrWhiteSpace(sql.CommandText)) 134 | { 135 | sqlBuilder.Append($" WHERE {sql.CommandText}"); 136 | pageBuilder.Append($" WHERE {sql.CommandText}"); 137 | } 138 | 139 | var parameters = DbSQLHelper.Convert(sql.Parameters); 140 | int total = Convert.ToInt32(DbSQLHelper.ExecuteScalar(pageBuilder.ToString(), parameters)); 141 | if (total > 1) 142 | throw new SingleOrDefaultException(); 143 | sqlBuilder.Append($" LIMIT 0,1"); 144 | 145 | T instance = DbSQLHelper.ExecuteList(sqlBuilder.ToString(), parameters).FirstOrDefault(); 146 | return instance; 147 | } 148 | 149 | public T FirstOrDefault() 150 | { 151 | var tableInfo = StoreBase.GetTableInfo(typeof(T)); 152 | var sql = ExpressionFactory.ToWhereSql(Predicate); 153 | 154 | var builder = new StringBuilder(); 155 | builder.Append($"SELECT {tableInfo.ColumnsComma} FROM {tableInfo.Name}"); 156 | if (!string.IsNullOrWhiteSpace(sql.CommandText)) 157 | builder.Append($" WHERE {sql.CommandText}"); 158 | if (OrderInfoList.Count > 0) 159 | builder.Append(StoreBase.BuildOrderSQL(OrderInfoList)); 160 | builder.Append($" LIMIT 0,1"); 161 | 162 | var parameters = DbSQLHelper.Convert(sql.Parameters); 163 | 164 | T instance = DbSQLHelper.ExecuteList(builder.ToString(), parameters).FirstOrDefault(); 165 | return instance; 166 | } 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.MSSQLServer/SQLServerQueryabel.cs: -------------------------------------------------------------------------------- 1 | using HSQL.Base; 2 | using HSQL.Const; 3 | using HSQL.Exceptions; 4 | using HSQL.Factory; 5 | using HSQL.Model; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Linq; 9 | using System.Linq.Expressions; 10 | using System.Reflection; 11 | using System.Text; 12 | 13 | namespace HSQL.MSSQLServer 14 | { 15 | public class SQLServerQueryabel : QueryabelBase, IQueryabel 16 | { 17 | public SQLServerQueryabel(IDbSQLHelper dbSQLHelper, Expression> predicate) 18 | { 19 | DbSQLHelper = dbSQLHelper; 20 | Predicate = predicate; 21 | } 22 | 23 | public IQueryabel ConditionAnd(Expression> condition) 24 | { 25 | if (Predicate == null) 26 | Predicate = condition; 27 | else 28 | Predicate = Predicate.AndAlso(condition); 29 | 30 | return this; 31 | } 32 | 33 | public IQueryabel ConditionOr(Expression> condition) 34 | { 35 | if (Predicate == null) 36 | Predicate = condition; 37 | else 38 | Predicate = Predicate.OrElse(condition); 39 | 40 | return this; 41 | } 42 | 43 | public int Count() 44 | { 45 | var sql = ExpressionFactory.ToWhereSql(Predicate); 46 | var tableInfo = StoreBase.GetTableInfo(typeof(T)); 47 | var builder = new StringBuilder($"SELECT COUNT(*) FROM {tableInfo.Name} WITH(NOLOCK)"); 48 | 49 | if (!string.IsNullOrWhiteSpace(sql.CommandText)) 50 | builder.Append($" WHERE {sql.CommandText}"); 51 | 52 | var parameters = DbSQLHelper.Convert(sql.Parameters); 53 | 54 | int total = Convert.ToInt32(DbSQLHelper.ExecuteScalar(builder.ToString(), parameters)); 55 | return total; 56 | } 57 | 58 | public bool Exists() 59 | { 60 | return Count() > 0; 61 | } 62 | 63 | public List ToList() 64 | { 65 | var tableInfo = StoreBase.GetTableInfo(typeof(T)); 66 | Sql sql = ExpressionFactory.ToWhereSql(Predicate); 67 | 68 | StringBuilder sqlStringBuilder = new StringBuilder(); 69 | sqlStringBuilder.Append($"SELECT {tableInfo.ColumnsComma} FROM {tableInfo.Name} WITH(NOLOCK)"); 70 | if (!string.IsNullOrWhiteSpace(sql.CommandText)) 71 | sqlStringBuilder.Append($" WHERE {sql.CommandText}"); 72 | 73 | if (OrderInfoList.Count > 0) 74 | sqlStringBuilder.Append(StoreBase.BuildOrderSQL(OrderInfoList)); 75 | 76 | List list = DbSQLHelper.ExecuteList(sqlStringBuilder.ToString(), DbSQLHelper.Convert(sql.Parameters)); 77 | return list; 78 | } 79 | 80 | public List ToList(int pageIndex, int pageSize) 81 | { 82 | var tableInfo = StoreBase.GetTableInfo(typeof(T)); 83 | int pageStart = (pageIndex - 1) * pageSize; 84 | Sql sql = ExpressionFactory.ToWhereSql(Predicate); 85 | 86 | var builder = new StringBuilder(); 87 | builder.Append($"SELECT {tableInfo.ColumnsComma} FROM {tableInfo.Name} WITH(NOLOCK)"); 88 | if (!string.IsNullOrWhiteSpace(sql.CommandText)) 89 | builder.Append($" WHERE {sql.CommandText}"); 90 | 91 | if (OrderInfoList.Count > 0) 92 | builder.Append(StoreBase.BuildOrderSQL(OrderInfoList)); 93 | else 94 | builder.Append($" ORDER BY {tableInfo.DefaultOrderColumnName}"); 95 | 96 | builder.Append($" OFFSET {pageStart} ROWS FETCH NEXT {pageSize} ROWS ONLY;"); 97 | 98 | List list = DbSQLHelper.ExecuteList(builder.ToString(), DbSQLHelper.Convert(sql.Parameters)); 99 | return list; 100 | } 101 | 102 | public List ToList(int pageIndex, int pageSize, out int total, out int totalPage) 103 | { 104 | var tableInfo = StoreBase.GetTableInfo(typeof(T)); 105 | Sql sql = ExpressionFactory.ToWhereSql(Predicate); 106 | 107 | int pageStart = (pageIndex - 1) * pageSize; 108 | 109 | StringBuilder sqlStringBuilder = new StringBuilder($"SELECT {tableInfo.ColumnsComma} FROM {tableInfo.Name} WITH(NOLOCK)"); 110 | StringBuilder pageStringBuilder = new StringBuilder($"SELECT COUNT(*) FROM {tableInfo.Name} WITH(NOLOCK)"); 111 | 112 | if (!string.IsNullOrWhiteSpace(sql.CommandText)) 113 | { 114 | sqlStringBuilder.Append($" WHERE {sql.CommandText}"); 115 | pageStringBuilder.Append($" WHERE {sql.CommandText}"); 116 | } 117 | pageStringBuilder.Append(";"); 118 | 119 | var parameters = DbSQLHelper.Convert(sql.Parameters); 120 | total = Convert.ToInt32(DbSQLHelper.ExecuteScalar(pageStringBuilder.ToString(), parameters)); 121 | totalPage = (total % pageSize == 0) ? (total / pageSize) : (total / pageSize + 1); 122 | 123 | if (OrderInfoList.Count > 0) 124 | sqlStringBuilder.Append(StoreBase.BuildOrderSQL(OrderInfoList)); 125 | else 126 | sqlStringBuilder.Append($" ORDER BY {tableInfo.DefaultOrderColumnName}"); 127 | 128 | sqlStringBuilder.Append($" OFFSET {pageStart} ROWS FETCH NEXT {pageSize} ROWS ONLY;"); 129 | 130 | List list = DbSQLHelper.ExecuteList(sqlStringBuilder.ToString(), parameters); 131 | 132 | return list; 133 | } 134 | 135 | public T SingleOrDefault() 136 | { 137 | var tableInfo = StoreBase.GetTableInfo(typeof(T)); 138 | Sql sql = ExpressionFactory.ToWhereSql(Predicate); 139 | 140 | StringBuilder sqlStringBuilder = new StringBuilder($"SELECT {tableInfo.ColumnsComma} FROM {tableInfo.Name} WITH(NOLOCK)"); 141 | StringBuilder pageStringBuilder = new StringBuilder($"SELECT COUNT(*) FROM {tableInfo.Name} WITH(NOLOCK)"); 142 | 143 | if (!string.IsNullOrWhiteSpace(sql.CommandText)) 144 | { 145 | sqlStringBuilder.Append($" WHERE {sql.CommandText}"); 146 | pageStringBuilder.Append($" WHERE {sql.CommandText}"); 147 | } 148 | pageStringBuilder.Append(";"); 149 | 150 | var parameters = DbSQLHelper.Convert(sql.Parameters); 151 | 152 | int total = Convert.ToInt32(DbSQLHelper.ExecuteScalar(pageStringBuilder.ToString(), parameters)); 153 | if (total > 1) 154 | throw new SingleOrDefaultException(); 155 | 156 | if (OrderInfoList.Count > 0) 157 | sqlStringBuilder.Append(StoreBase.BuildOrderSQL(OrderInfoList)); 158 | else 159 | sqlStringBuilder.Append($" ORDER BY {tableInfo.DefaultOrderColumnName}"); 160 | 161 | sqlStringBuilder.Append($" OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY"); 162 | 163 | T instance = DbSQLHelper.ExecuteList(sqlStringBuilder.ToString(), parameters).FirstOrDefault(); 164 | return instance; 165 | } 166 | 167 | public T FirstOrDefault() 168 | { 169 | var tableInfo = StoreBase.GetTableInfo(typeof(T)); 170 | Sql sql = ExpressionFactory.ToWhereSql(Predicate); 171 | 172 | var builder = new StringBuilder(); 173 | builder.Append($"SELECT {tableInfo.ColumnsComma} FROM {tableInfo.Name} WITH(NOLOCK)"); 174 | if (!string.IsNullOrWhiteSpace(sql.CommandText)) 175 | builder.Append($" WHERE {sql.CommandText}"); 176 | if (OrderInfoList.Count > 0) 177 | builder.Append(StoreBase.BuildOrderSQL(OrderInfoList)); 178 | else 179 | builder.Append($" ORDER BY {tableInfo.DefaultOrderColumnName}"); 180 | builder.Append($" OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY"); 181 | 182 | var parameters = DbSQLHelper.Convert(sql.Parameters); 183 | 184 | T instance = DbSQLHelper.ExecuteList(builder.ToString(), parameters).FirstOrDefault(); 185 | return instance; 186 | } 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/HSQL.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | HSQL 5 | 6 | 7 | 8 | 9 | 是否在控制台输出Sql语句 10 | 11 | 12 | 13 | 14 | 是否开启事务 15 | 16 | 17 | 18 | 19 | SQL帮助对象 20 | 21 | 22 | 23 | 24 | 构建连接字符串 25 | 26 | 服务器地址 27 | 数据库 28 | 用户名 29 | 密码 30 | 连接字符串 31 | 32 | 33 | 34 | 事务调用 35 | 36 | 方法体 37 | 38 | 39 | 40 | 设置在执行操作的时候是否将Sql语句打印到控制台 41 | 42 | True 为打印,False 为不打印 43 | 44 | 45 | 46 | 执行增删改操作 47 | 48 | 连接对象 49 | 是否在控制台打印Sql语句 50 | 执行命令 51 | 参数 52 | 执行完成后,影响行数 53 | 54 | 55 | 56 | 在控制台打印Sql语句 57 | 58 | 是否打印SQL语句 59 | 将要打印的Sql语句 60 | 61 | 62 | 63 | 设置在执行操作的时候是否将Sql语句打印到控制台 64 | 65 | True 为打印,False 为不打印 66 | 67 | 68 | 69 | 执行新增操作 70 | 71 | 类型 72 | 要新增的实例 73 | 是否新增成功 74 | 75 | 76 | 77 | 执行更新操作 78 | 79 | 类型 80 | 条件表达式,可理解为 SQL 语句中的 WHERE。如:WHERE age = 16 可写为 x=> x.Age = 16 81 | 目标表达式,可理解为SQL 语句中的 SET。如:SET age = 16 , name = '张三' 可写为 new Student(){ Age = 16 , Name = "张三" } 82 | 是否更新成功 83 | 84 | 85 | 86 | 执行删除操作 87 | 88 | 类型 89 | 条件表达式 90 | 是否删除成功 91 | 92 | 93 | 94 | 事务调用 95 | 96 | 方法体 97 | 98 | 99 | 100 | 无条件查询 101 | 102 | 类型 103 | 104 | 105 | 106 | 无条件查询 107 | 108 | 查询条件表达式 109 | 类型 110 | 111 | 112 | 113 | 使用SQL语句查询,并得到结果集 114 | 115 | SQL语句 116 | 117 | 118 | 119 | 使用SQL语句查询,并得到结果集 120 | 121 | SQL语句 122 | 参数 123 | 124 | 125 | 126 | 清空表 127 | 128 | 类型 129 | 130 | 131 | 132 | 查询时添加 AND 条件 133 | 134 | 条件 135 | 136 | 137 | 138 | 查询时添加 Or 条件 139 | 140 | 条件 141 | 142 | 143 | 144 | 取得符合查询条件的第一条数据 145 | 146 | 147 | 148 | 149 | 取得符合查询条件的第一条数据,如符合条件的数据不为1条,则抛出异常 150 | 151 | 152 | 153 | 154 | 取得符合查询条件的数据的数量 155 | 156 | 157 | 158 | 159 | 检查符合查询条件的数据是否存在 160 | 161 | 162 | 163 | 164 | 获取数据 165 | 166 | 167 | 168 | 169 | 分页获取数据 170 | 171 | 页号 172 | 每页记录条数 173 | 174 | 175 | 176 | 分页获取数据 177 | 178 | 页号 179 | 每页记录条数 180 | 总记录条数 181 | 总页数 182 | 183 | 184 | 185 | 正排序 186 | 187 | 排序字段 188 | 189 | 190 | 191 | 倒排序 192 | 193 | 排序字段 194 | 195 | 196 | 197 | 倒排序 198 | 199 | 排序方式 200 | 排序字段 201 | 202 | 203 | 204 | -------------------------------------------------------------------------------- /code/HSQL/HSQL.Test/UnitTestDataBase.cs: -------------------------------------------------------------------------------- 1 | using HSQL.MySQL; 2 | using HSQL.Test.TestDataBaseModel; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using System.Collections.Generic; 5 | 6 | namespace HSQL.Test 7 | { 8 | [TestClass] 9 | public class UnitTestDataBase 10 | { 11 | IDbContext dbContext = new DbContext("127.0.0.1", "test", "root", "123456", 3, true); 12 | 13 | [TestMethod] 14 | public void TestInsert() 15 | { 16 | var result = dbContext.Insert(new Student() 17 | { 18 | Name = "zhangsan", 19 | Age = 18, 20 | SchoolId = "123" 21 | }); 22 | 23 | Assert.IsTrue(result); 24 | } 25 | 26 | [TestMethod] 27 | public void TestUpdate() 28 | { 29 | dbContext.Delete(x => x.Id.Contains("test_'update_list")); 30 | 31 | var insertResult = dbContext.Insert(new Student() 32 | { 33 | Id = $"test_'update_list", 34 | Name = "zhangsan", 35 | Age = 18, 36 | SchoolId = "123" 37 | }); 38 | Assert.AreEqual(true, insertResult); 39 | 40 | var updateResult = dbContext.Update(x => x.Id.Contains("test_'update_list"), new Student() { Age = 19 }); 41 | Assert.AreEqual(true, updateResult); 42 | 43 | var deleteResult = dbContext.Delete(x => x.Id.Contains("test_'update_list")); 44 | Assert.AreEqual(true, deleteResult); 45 | } 46 | 47 | [TestMethod] 48 | public void TestQuerySingle() 49 | { 50 | var s = new Student() 51 | { 52 | Id = "test_query_single", 53 | Name = "zhangsan", 54 | Age = 19 55 | }; 56 | 57 | dbContext.Delete(x => x.Id == s.Id); 58 | 59 | var result = dbContext.Insert(s); 60 | 61 | var student = dbContext.Query(x => x.Id == s.Id).FirstOrDefault(); 62 | Assert.IsNotNull(student); 63 | 64 | Assert.AreEqual(19, student.Age); 65 | Assert.AreEqual("test_query_single", student.Id); 66 | Assert.AreEqual("zhangsan", student.Name); 67 | } 68 | 69 | [TestMethod] 70 | public void TestQueryOrderBy() 71 | { 72 | var list = dbContext.Query().OrderBy(x => x.Id).ToList(); 73 | } 74 | 75 | [TestMethod] 76 | public void TestQueryThenOrderByDescending() 77 | { 78 | var list = dbContext.Query().OrderBy(x => x.Id).ThenOrderByDescending(x => x.Name).ToList(); 79 | } 80 | 81 | 82 | [TestMethod] 83 | public void TestQueryAll() 84 | { 85 | 86 | dbContext.Query().OrderBy(x => x.Id).ToList(); 87 | 88 | dbContext.Delete(x => !x.Id.Contains("")); 89 | 90 | 91 | dbContext.Insert(new School() 92 | { 93 | Id = $"test_query_list123", 94 | Name = "sdf" 95 | }); 96 | dbContext.Insert(new Student() 97 | { 98 | Id = $"test_query_list", 99 | SchoolId = "test_query_list123", 100 | Name = "zhangsan", 101 | Age = 19 102 | }); 103 | 104 | 105 | 106 | var list = dbContext.Query().ToList(); 107 | 108 | Assert.IsTrue(list.Count > 0); 109 | } 110 | 111 | [TestMethod] 112 | public void TestQueryList() 113 | { 114 | dbContext.Delete(x => x.Id.Contains("test_query_list")); 115 | 116 | 117 | dbContext.Insert(new Student() 118 | { 119 | Id = $"test_query_list", 120 | Name = "zhangsan", 121 | Age = 19 122 | }); 123 | var list = dbContext.Query(x => x.Age == 19 && x.Id.Contains("test_query_list")).ConditionAnd(x => x.Name == "zhangsan").ToList(); 124 | 125 | list.ForEach(x => 126 | { 127 | Assert.AreEqual(19, x.Age); 128 | Assert.IsTrue(x.Id.Contains("test_query_list")); 129 | Assert.AreEqual("zhangsan", x.Name); 130 | }); 131 | Assert.IsTrue(list.Count == 1); 132 | } 133 | 134 | [TestMethod] 135 | public void TestQueryListByIn() 136 | { 137 | dbContext.Delete(x => x.Id.Contains("test_query_in_list")); 138 | 139 | dbContext.Insert(new Student() 140 | { 141 | Id = $"test_query_in_list", 142 | Name = "zhangsan", 143 | Age = 19 144 | }); 145 | var studentList = new List(); 146 | var listNo = dbContext.Query(x => studentList.Contains(x.Id)).ConditionAnd(x => x.Id == "test_query_in_list" && x.Name == "zhangsan").ToList(); 147 | 148 | Assert.IsTrue(listNo.Count == 1); 149 | } 150 | 151 | [TestMethod] 152 | public void TestQueryPageList() 153 | { 154 | 155 | dbContext.Delete(x => x.Id.Contains("test_query_page_list")); 156 | 157 | dbContext.Insert(new Student() 158 | { 159 | Id = $"test_query_page_list", 160 | Name = "zhangsan", 161 | Age = 19 162 | }); 163 | var list = dbContext.Query(x => x.Age == 19 && x.Id.Contains("test_query_page_list")) 164 | .ConditionAnd(x => x.Name == "zhangsan") 165 | .OrderBy(x => x.Age) 166 | .ToList(1, 10); 167 | 168 | list.ForEach(x => 169 | { 170 | Assert.AreEqual(19, x.Age); 171 | Assert.IsTrue(x.Id.Contains("test_query_page_list")); 172 | Assert.AreEqual("zhangsan", x.Name); 173 | }); 174 | } 175 | 176 | [TestMethod] 177 | public void TestQueryPageList2() 178 | { 179 | 180 | dbContext.Delete(x => x.Id.Contains("test_query_page_2_list")); 181 | 182 | dbContext.Insert(new Student() 183 | { 184 | Id = $"test_query_page_2_list", 185 | Name = "zhangsan", 186 | Age = 19 187 | }); 188 | 189 | var total = 0; 190 | var totalPage = 0; 191 | var list = dbContext.Query(x => x.Age == 19 && x.Id.Contains("test_query_page_2_list")) 192 | .ConditionAnd(x => x.Name == "zhangsan") 193 | .ToList(2, 10, out total, out totalPage); 194 | 195 | list.ForEach(x => 196 | { 197 | Assert.AreEqual(19, x.Age); 198 | Assert.IsTrue(x.Id.Contains("test_query_page_2_list")); 199 | Assert.AreEqual("zhangsan", x.Name); 200 | }); 201 | } 202 | 203 | [TestMethod] 204 | public void TestDelete() 205 | { 206 | 207 | var result = dbContext.Delete(x => x.Age > 0); 208 | 209 | Assert.AreEqual(true, result); 210 | } 211 | 212 | [TestMethod] 213 | public void TestQuerySQL() 214 | { 215 | 216 | var list = dbContext.Query("SELECT * FROM t_student;"); 217 | 218 | Assert.AreNotEqual(list, null); 219 | } 220 | 221 | [TestMethod] 222 | public void TestQuerySQLByParameters() 223 | { 224 | var student = dbContext.Query(x => x.Id.Equals("test_query_sin'gle")).FirstOrDefault(); 225 | 226 | var list = dbContext.Query("SELECT t.id,t.name,s.id AS school_id FROM t_student AS t LEFT JOIN t_school AS s ON t.school_id = s.id WHERE t.id = @id AND t.age > @age;", new 227 | { 228 | id = "test_query_list", 229 | age = 1 230 | }); 231 | 232 | Assert.AreNotEqual(list, null); 233 | 234 | } 235 | 236 | [TestMethod] 237 | public void TestConsolePrintSQL() 238 | { 239 | dbContext.SetConsolePrintSql(true); 240 | var student = dbContext.Query(x => x.Id.Equals("test_query_single")).FirstOrDefault(); 241 | } 242 | } 243 | } 244 | -------------------------------------------------------------------------------- /code/HSQL/HSQL/Factory/ExpressionFactory.cs: -------------------------------------------------------------------------------- 1 | using HSQL.Attribute; 2 | using HSQL.Base; 3 | using HSQL.Const; 4 | using HSQL.Exceptions; 5 | using HSQL.Model; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Data; 9 | using System.Linq; 10 | using System.Linq.Expressions; 11 | using System.Reflection; 12 | 13 | namespace HSQL.Factory 14 | { 15 | public class ExpressionFactory 16 | { 17 | public static List GetColumnList(T instance) 18 | { 19 | List list = new List(); 20 | 21 | foreach (PropertyInfo property in instance.GetType().GetProperties()) 22 | { 23 | foreach (ColumnAttribute attribute in property.GetCustomAttributes(TypeOfConst.ColumnAttribute, true)) 24 | { 25 | var value = property.GetValue(instance, null); 26 | 27 | if (property.PropertyType == TypeOfConst.String) 28 | { 29 | list.Add(new Column(attribute.Name, value == null ? string.Empty : value)); 30 | } 31 | else if (property.PropertyType == TypeOfConst.Int 32 | || property.PropertyType == TypeOfConst.UInt 33 | || property.PropertyType == TypeOfConst.Long 34 | || property.PropertyType == TypeOfConst.Float 35 | || property.PropertyType == TypeOfConst.Double 36 | || property.PropertyType == TypeOfConst.Decimal) 37 | { 38 | list.Add(new Column(attribute.Name, value == null ? 0 : value)); 39 | } 40 | else if (property.PropertyType == TypeOfConst.ByteArray 41 | || property.PropertyType == TypeOfConst.DateTime) 42 | { 43 | list.Add(new Column(attribute.Name, value)); 44 | } 45 | else 46 | { 47 | list.Add(new Column(attribute.Name, value)); 48 | } 49 | } 50 | } 51 | if (list.Count <= 0) 52 | throw new Exception("缺少列名"); 53 | return list; 54 | } 55 | 56 | public static List GetColumnListWithOutNull(T instance) 57 | { 58 | List list = new List(); 59 | 60 | foreach (PropertyInfo property in instance.GetType().GetProperties()) 61 | { 62 | foreach (ColumnAttribute attribute in property.GetCustomAttributes(TypeOfConst.ColumnAttribute, true)) 63 | { 64 | var value = property.GetValue(instance, null); 65 | if (value == null) 66 | continue; 67 | 68 | if (property.PropertyType == TypeOfConst.String 69 | || property.PropertyType == TypeOfConst.ByteArray 70 | || property.PropertyType == TypeOfConst.DateTime) 71 | { 72 | list.Add(new Column(attribute.Name, value)); 73 | } 74 | else if (property.PropertyType == TypeOfConst.Int 75 | || property.PropertyType == TypeOfConst.UInt 76 | || property.PropertyType == TypeOfConst.Long 77 | || property.PropertyType == TypeOfConst.Float 78 | || property.PropertyType == TypeOfConst.Double 79 | || property.PropertyType == TypeOfConst.Decimal) 80 | { 81 | if (Convert.ToInt32(value) != 0) 82 | list.Add(new Column(attribute.Name, value)); 83 | } 84 | } 85 | } 86 | if (list.Count <= 0) 87 | throw new Exception("缺少列名"); 88 | return list; 89 | } 90 | 91 | public static Sql ToWhereSql(Expression expression) 92 | { 93 | if (expression == null) 94 | return new Sql(); 95 | 96 | Sql sql = ResolveWhereSql(expression); 97 | return sql; 98 | } 99 | 100 | 101 | private static Sql ResolveWhereSql(Expression expression) 102 | { 103 | if (expression == null) 104 | throw new ExpressionException(); 105 | 106 | if (expression is LambdaExpression) 107 | return ResolveWhereSql(((LambdaExpression)expression).Body); 108 | else if (expression is BinaryExpression) 109 | { 110 | BinaryExpression binaryExpression = (BinaryExpression)expression; 111 | 112 | switch (expression.NodeType) 113 | { 114 | case ExpressionType.AndAlso: 115 | case ExpressionType.OrElse: 116 | { 117 | Sql left = ResolveWhereSql(binaryExpression.Left); 118 | Sql right = ResolveWhereSql(binaryExpression.Right); 119 | 120 | if (left == null) 121 | return right; 122 | if (right == null) 123 | return left; 124 | 125 | Sql sql = new Sql(Combining(left.CommandText, ResolveSymbol(expression.NodeType), right.CommandText)); 126 | sql.Parameters.AddRange(left.Parameters); 127 | sql.Parameters.AddRange(right.Parameters); 128 | return sql; 129 | } 130 | case ExpressionType.Equal: 131 | case ExpressionType.NotEqual: 132 | case ExpressionType.GreaterThanOrEqual: 133 | case ExpressionType.GreaterThan: 134 | case ExpressionType.LessThanOrEqual: 135 | case ExpressionType.LessThan: 136 | { 137 | string right = ""; 138 | 139 | if (binaryExpression.Right.NodeType == ExpressionType.MemberAccess) 140 | right = ResolveMemberValue((MemberExpression)binaryExpression.Right, false); 141 | else if (binaryExpression.Right.NodeType == ExpressionType.Constant) 142 | { 143 | string value = ResolveConstant((ConstantExpression)binaryExpression.Right); 144 | if (binaryExpression.Right.Type == TypeOfConst.Int 145 | || binaryExpression.Right.Type == TypeOfConst.UInt 146 | || binaryExpression.Right.Type == TypeOfConst.Long 147 | || binaryExpression.Right.Type == TypeOfConst.Float 148 | || binaryExpression.Right.Type == TypeOfConst.Double 149 | || binaryExpression.Right.Type == TypeOfConst.Decimal) 150 | right = value; 151 | else if (binaryExpression.Right.Type == TypeOfConst.String) 152 | right = value; 153 | else 154 | throw new ExpressionException(); 155 | } 156 | else if (binaryExpression.Right.NodeType == ExpressionType.Call) 157 | right = ResolveMethodCall((MethodCallExpression)binaryExpression.Right).CommandText; 158 | else if (binaryExpression.Right.NodeType == ExpressionType.Convert) 159 | { 160 | var operand = (binaryExpression.Right as UnaryExpression).Operand as MemberExpression; 161 | right = ResolveMemberValue(operand); 162 | } 163 | else 164 | throw new ExpressionException(); 165 | 166 | string memberName = ResolveMemberName((MemberExpression)binaryExpression.Left); 167 | Sql sql = new Sql(Combining(memberName, ResolveSymbol(expression.NodeType), $"@{memberName}")); 168 | sql.Parameters.Add(new Parameter(memberName, right)); 169 | return sql; 170 | } 171 | default: 172 | throw new ExpressionException(); 173 | } 174 | } 175 | else if (expression is MethodCallExpression) 176 | { 177 | return ResolveMethodCall((MethodCallExpression)expression); 178 | } 179 | else if (expression is ConstantExpression) 180 | { 181 | return new Sql(ResolveConstant((ConstantExpression)expression)); 182 | } 183 | else if (expression is UnaryExpression) 184 | { 185 | return ResolveUnary((UnaryExpression)expression); 186 | } 187 | throw new ExpressionException(); 188 | } 189 | 190 | 191 | 192 | private static Sql ResolveMethodCall(MethodCallExpression expression) 193 | { 194 | if (expression.Object == null) 195 | return new Sql(Eval(expression)); 196 | else if (expression.Object.Type.IsGenericType && expression.Method.Name.Equals(KeywordConst.Contains)) 197 | return ResolveMethodCallIn(expression); 198 | else 199 | return ResolveMethodCallEqualsOrLike(expression); 200 | 201 | throw new ExpressionException(); 202 | } 203 | 204 | private static Sql ResolveMethodCallIn(MethodCallExpression expression) 205 | { 206 | string left = StoreBase.GetColumnName((MemberExpression)expression.Arguments[0]); 207 | string right = ""; 208 | if (expression.Object.NodeType == ExpressionType.MemberAccess) 209 | right = ResolveMemberValue((MemberExpression)expression.Object); 210 | else if (expression.Object.NodeType == ExpressionType.Call) 211 | right = ResolveMethodCall((MethodCallExpression)expression.Object).CommandText; 212 | else 213 | throw new ExpressionException(); 214 | 215 | if (string.IsNullOrWhiteSpace(right)) 216 | return new Sql(Combining(left, KeywordConst.IN, "('')")); 217 | 218 | return new Sql(Combining(left, KeywordConst.IN, $"({right})")); 219 | } 220 | 221 | private static Sql ResolveMethodCallEqualsOrLike(MethodCallExpression expression) 222 | { 223 | string left = StoreBase.GetColumnName((MemberExpression)expression.Object); 224 | string right = ""; 225 | if (expression.Arguments[0] is MemberExpression) 226 | right = Eval((MemberExpression)expression.Arguments[0]); 227 | else if (expression.Arguments[0] is ConstantExpression) 228 | right = ResolveConstant((ConstantExpression)expression.Arguments[0]); 229 | else if (expression.Arguments[0] is MethodCallExpression) 230 | right = ResolveMethodCall((MethodCallExpression)expression.Arguments[0]).CommandText; 231 | else 232 | throw new ExpressionException(); 233 | 234 | Sql sql = new Sql(); 235 | switch (expression.Method.Name) 236 | { 237 | case KeywordConst.Equals: 238 | sql.CommandText = Combining(left, "=", $"@{left}"); 239 | sql.Parameters.Add(new Parameter(left, right)); 240 | return sql; 241 | case KeywordConst.Contains: 242 | sql.CommandText = Combining(left, KeywordConst.LIKE, $"@{left}"); 243 | sql.Parameters.Add(new Parameter(left, $"%{right}%")); 244 | return sql; 245 | default: 246 | throw new ExpressionException(); 247 | } 248 | } 249 | 250 | private static string ResolveMemberName(MemberExpression expression) 251 | { 252 | return StoreBase.GetColumnName(expression); 253 | } 254 | 255 | private static string ResolveMemberValue(MemberExpression expression, bool onlyValue = true) 256 | { 257 | return Eval(expression, onlyValue); 258 | } 259 | 260 | private static string ResolveConvertValue(MemberExpression expression, bool onlyValue = true) 261 | { 262 | return Eval(expression, onlyValue); 263 | } 264 | 265 | private static string ResolveConstant(ConstantExpression expression) 266 | { 267 | return expression.Value.ToString(); 268 | } 269 | 270 | private static Sql ResolveUnary(UnaryExpression expression) 271 | { 272 | if (expression.NodeType == ExpressionType.Not) 273 | { 274 | Sql sql = ResolveMethodCall((MethodCallExpression)expression.Operand); 275 | sql.CommandText = sql.CommandText.Replace(" = ", " != "); 276 | return sql; 277 | } 278 | throw new ExpressionException(); 279 | } 280 | 281 | private static string ResolveSymbol(ExpressionType nodeType) 282 | { 283 | switch (nodeType) 284 | { 285 | case ExpressionType.AndAlso: 286 | return KeywordConst.AND; 287 | case ExpressionType.OrElse: 288 | return KeywordConst.OR; 289 | case ExpressionType.Equal: 290 | return "="; 291 | case ExpressionType.NotEqual: 292 | return "!="; 293 | case ExpressionType.GreaterThanOrEqual: 294 | return ">="; 295 | case ExpressionType.GreaterThan: 296 | return ">"; 297 | case ExpressionType.LessThanOrEqual: 298 | return "<="; 299 | case ExpressionType.LessThan: 300 | return "<"; 301 | default: 302 | throw new ExpressionException(); 303 | } 304 | } 305 | 306 | private static string Eval(Expression expression, bool onlyValue = true) 307 | { 308 | if (expression.Type == TypeOfConst.Int) 309 | return Expression.Lambda>(Expression.Convert(expression, TypeOfConst.Int)).Compile().Invoke().ToString(); 310 | else if (expression.Type == TypeOfConst.Long) 311 | return Expression.Lambda>(Expression.Convert(expression, TypeOfConst.Long)).Compile().Invoke().ToString(); 312 | else if (expression.Type == TypeOfConst.Decimal) 313 | return Expression.Lambda>(Expression.Convert(expression, TypeOfConst.Decimal)).Compile().Invoke().ToString(); 314 | else if (expression.Type == TypeOfConst.Float) 315 | return Expression.Lambda>(Expression.Convert(expression, TypeOfConst.Float)).Compile().Invoke().ToString(); 316 | else if (expression.Type == TypeOfConst.Double) 317 | return Expression.Lambda>(Expression.Convert(expression, TypeOfConst.Double)).Compile().Invoke().ToString(); 318 | if (expression.Type == TypeOfConst.DateTime) 319 | return $"'{Expression.Lambda>(Expression.Convert(expression, TypeOfConst.DateTime)).Compile().Invoke().ToString()}'"; 320 | else if (expression.Type == TypeOfConst.String) 321 | { 322 | return Expression.Lambda>(Expression.Convert(expression, TypeOfConst.String)).Compile().Invoke(); 323 | } 324 | else if (expression.Type == TypeOfConst.ListInt) 325 | return string.Join(",", Expression.Lambda>>(Expression.Convert(expression, TypeOfConst.ListInt)).Compile().Invoke().Select(x => string.Format("{0}", x))); 326 | else if (expression.Type == TypeOfConst.ListLong) 327 | return string.Join(",", Expression.Lambda>>(Expression.Convert(expression, TypeOfConst.ListLong)).Compile().Invoke().Select(x => string.Format("{0}", x))); 328 | else if (expression.Type == TypeOfConst.ListDecimal) 329 | return string.Join(",", Expression.Lambda>>(Expression.Convert(expression, TypeOfConst.ListDecimal)).Compile().Invoke().Select(x => string.Format("{0}", x))); 330 | else if (expression.Type == TypeOfConst.ListFloat) 331 | return string.Join(",", Expression.Lambda>>(Expression.Convert(expression, TypeOfConst.ListFloat)).Compile().Invoke().Select(x => string.Format("{0}", x))); 332 | else if (expression.Type == TypeOfConst.ListDouble) 333 | return string.Join(",", Expression.Lambda>>(Expression.Convert(expression, TypeOfConst.ListDouble)).Compile().Invoke().Select(x => string.Format("{0}", x))); 334 | else if (expression.Type == TypeOfConst.ListString) 335 | return string.Join(",", Expression.Lambda>>(Expression.Convert(expression, TypeOfConst.ListString)).Compile().Invoke().Select(x => string.Format("'{0}'", x))); 336 | else 337 | { 338 | if (expression.Type.BaseType == typeof(Enum)) 339 | { 340 | return Expression.Lambda>(Expression.Convert(expression, TypeOfConst.Int)).Compile().Invoke().ToString(); 341 | } 342 | } 343 | 344 | throw new ExpressionException(); 345 | } 346 | 347 | private static string Combining(string left, string symbol, string right) 348 | { 349 | if (string.IsNullOrWhiteSpace(left) && string.IsNullOrWhiteSpace(right)) 350 | return string.Empty; 351 | if (string.IsNullOrWhiteSpace(left)) 352 | return right; 353 | if (string.IsNullOrWhiteSpace(right)) 354 | return left; 355 | 356 | if (symbol.Equals(">") 357 | || symbol.Equals(">=") 358 | || symbol.Equals("=") 359 | || symbol.Equals("!=") 360 | || symbol.Equals("<") 361 | || symbol.Equals("<=") 362 | || symbol.Equals(KeywordConst.IN) 363 | || symbol.Equals(KeywordConst.LIKE) 364 | || symbol.Equals(KeywordConst.AND)) 365 | { 366 | return $"{left} {symbol} {right}"; 367 | } 368 | else if (symbol.Equals(KeywordConst.OR)) 369 | { 370 | if (!IsNormalExpression(left)) 371 | left = $"({left})"; 372 | if (!IsNormalExpression(right)) 373 | right = $"({right})"; 374 | 375 | return $"({left} {symbol} {right})"; 376 | } 377 | return $"{left} {symbol} {right}"; 378 | } 379 | 380 | private static bool IsNormalExpression(string text) 381 | { 382 | if (text.IndexOf("(") == 0 && text.LastIndexOf(")") == text.Length - 1) 383 | return true; 384 | 385 | int count = 0; 386 | 387 | count += text.IndexOf(" > ") > -1 ? 1 : 0; 388 | count += text.IndexOf(" >= ") > -1 ? 1 : 0; 389 | count += text.IndexOf(" = ") > -1 ? 1 : 0; 390 | count += text.IndexOf(" != ") > -1 ? 1 : 0; 391 | count += text.IndexOf(" < ") > -1 ? 1 : 0; 392 | count += text.IndexOf(" <= ") > -1 ? 1 : 0; 393 | count += text.IndexOf(" IN ") > -1 ? 1 : 0; 394 | count += text.IndexOf(" LIKE ") > -1 ? 1 : 0; 395 | 396 | bool isNormal = count == 1; 397 | return isNormal; 398 | } 399 | 400 | } 401 | } 402 | --------------------------------------------------------------------------------