调整一下数据库表基类,将一些静态方法抽离出来到sqlhelper类

simpledesign
nxiaoxiao 1 year ago
parent 2771293732
commit 192dbff619

@ -1,7 +1,7 @@
namespace OMS.NET.DbClass namespace OMS.NET.DbClass
{ {
[Table("map_data")] [Table("map_data")]
public class Map : BaseObject public class Map : SqlTable
{ {
[Column("id", true)] // Primary Key and Identity false [Column("id", true)] // Primary Key and Identity false
public string Id { get; set; } public string Id { get; set; }

@ -1,8 +1,7 @@
using System.Reflection; using System.Reflection;
using MySql.Data.MySqlClient; using MySql.Data.MySqlClient;
using OMS.NET.Common; using OMS.NET.Common;
namespace OMS.NET.DbClass namespace OMS.NET.DbClass{
{
[AttributeUsage(AttributeTargets.Class, Inherited = false)] [AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class TableAttribute : Attribute public class TableAttribute : Attribute
{ {
@ -27,15 +26,15 @@ namespace OMS.NET.DbClass
IsIdentity = isIdentity; IsIdentity = isIdentity;
} }
} }
public class BaseObject
{ public class SqlHelper{
private static string GetTableName(Type type) public static string GetTableName(Type type)
{ {
var attr = type.GetCustomAttribute<TableAttribute>(); var attr = type.GetCustomAttribute<TableAttribute>();
return attr?.TableName ?? throw new Exception($"{type.Name} 没有指定数据表"); return attr?.TableName ?? throw new Exception($"{type.Name} 没有指定数据表");
} }
private static IEnumerable<PropertyInfo> GetProperties(Type type) public static IEnumerable<PropertyInfo> GetProperties(Type type)
{ {
return type.GetProperties() return type.GetProperties()
.Where(p => p.GetCustomAttribute<ColumnAttribute>() != null); .Where(p => p.GetCustomAttribute<ColumnAttribute>() != null);
@ -72,7 +71,7 @@ namespace OMS.NET.DbClass
return (primaryKey.GetCustomAttribute<ColumnAttribute>()!.IsIdentity == true) ? null : primaryKey; return (primaryKey.GetCustomAttribute<ColumnAttribute>()!.IsIdentity == true) ? null : primaryKey;
} }
private static string GetInsertSql(Type type) public static string GetInsertSql(Type type)
{ {
var tableName = GetTableName(type); var tableName = GetTableName(type);
var identityKey = GetIdentityKeyProperty(type); var identityKey = GetIdentityKeyProperty(type);
@ -91,7 +90,7 @@ namespace OMS.NET.DbClass
return $"INSERT INTO {tableName} ({string.Join(", ", columns)}) VALUES ({string.Join(", ", values)})"; return $"INSERT INTO {tableName} ({string.Join(", ", columns)}) VALUES ({string.Join(", ", values)})";
} }
private static string GetUpdateSql(Type type) public static string GetUpdateSql(Type type)
{ {
var tableName = GetTableName(type); var tableName = GetTableName(type);
var setClause = string.Join(", ", var setClause = string.Join(", ",
@ -103,7 +102,7 @@ namespace OMS.NET.DbClass
return $"UPDATE {tableName} SET {setClause} WHERE {whereClause}"; return $"UPDATE {tableName} SET {setClause} WHERE {whereClause}";
} }
private static string GetDeleteSql(Type type) public static string GetDeleteSql(Type type)
{ {
var tableName = GetTableName(type); var tableName = GetTableName(type);
var primaryKey = GetPrimaryKeyProperties(type); var primaryKey = GetPrimaryKeyProperties(type);
@ -112,7 +111,7 @@ namespace OMS.NET.DbClass
return $"DELETE FROM {tableName} WHERE {whereClause}"; return $"DELETE FROM {tableName} WHERE {whereClause}";
} }
private static string GetSelectSql(Type type) public static string GetSelectSql(Type type)
{ {
var tableName = GetTableName(type); var tableName = GetTableName(type);
var columns = string.Join(", ", var columns = string.Join(", ",
@ -122,7 +121,7 @@ namespace OMS.NET.DbClass
return $"SELECT {columns} FROM {tableName}"; return $"SELECT {columns} FROM {tableName}";
} }
private static string GetSelectSqlWithPrimaryKey(Type type) public static string GetSelectSqlWithPrimaryKey(Type type)
{ {
var tableName = GetTableName(type); var tableName = GetTableName(type);
var columns = string.Join(", ", var columns = string.Join(", ",
@ -134,59 +133,7 @@ namespace OMS.NET.DbClass
return $"SELECT {columns} FROM {tableName} WHERE {whereClause}"; return $"SELECT {columns} FROM {tableName} WHERE {whereClause}";
} }
public void Test() public static IEnumerable<T> SelectAll<T>() where T : SqlTable, new()
{
Console.WriteLine("===========this is a test area=================");
Console.WriteLine(GetInsertSql(GetType()));
Console.WriteLine(GetDeleteSql(GetType()));
Console.WriteLine(GetUpdateSql(GetType()));
Console.WriteLine(GetSelectSql(GetType()));
Console.WriteLine(GetSelectSqlWithPrimaryKey(GetType()));
Console.WriteLine("===========this is a test area=================");
}
public virtual void Insert()
{
var type = GetType();
var insertSql = GetInsertSql(GetType());
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open(); // 确保在执行命令之前打开连接
using var command = new MySqlCommand(insertSql, connection);
AddParameters(command);
Console.WriteLine($"SQL: {command.CommandText}");
foreach (MySqlParameter param in command.Parameters)
{
Console.WriteLine($"Parameter: {param.ParameterName}, Value: {param.Value}");
}
command.ExecuteNonQuery();
Log.Info($"{GetTableName(type)}数据表插入({string.Join(',', ShowDetail())})");
}
public virtual void Update()
{
var type = GetType();
var updateSql = GetUpdateSql(GetType());
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open(); // 确保在执行命令之前打开连接
using var command = new MySqlCommand(updateSql, connection);
AddParameters(command);
command.ExecuteNonQuery();
Log.Info($"{GetTableName(type)}数据表修改({string.Join(',', ShowDetail())})");
}
public virtual void Delete()
{
var type = GetType();
var deleteSql = GetDeleteSql(GetType());
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open(); // 确保在执行命令之前打开连接
using var command = new MySqlCommand(deleteSql, connection);
AddParameters(command);
command.ExecuteNonQuery();
Log.Info($"{GetTableName(type)}数据表删除({string.Join(',', ShowDetail())})");
}
public static IEnumerable<T> SelectAll<T>() where T : BaseObject, new()
{ {
var type = typeof(T); var type = typeof(T);
var selectSql = GetSelectSql(type); var selectSql = GetSelectSql(type);
@ -205,7 +152,21 @@ namespace OMS.NET.DbClass
return results; return results;
} }
public static T? Get<T>(object key) where T : BaseObject, new() private static void PopulateObject(MySqlDataReader reader, SqlTable obj)
{
var type = obj.GetType();
foreach (var property in GetProperties(type))
{
var columnAttr = property.GetCustomAttribute<ColumnAttribute>()!;
var value = reader[columnAttr.ColumnName];
if (value != DBNull.Value)
{
property.SetValue(obj, Convert.ChangeType(value, property.PropertyType));
}
}
}
public static T? Get<T>(object key) where T : SqlTable, new()
{ {
var type = typeof(T); var type = typeof(T);
var selectSql = GetSelectSqlWithPrimaryKey(type); var selectSql = GetSelectSqlWithPrimaryKey(type);
@ -223,33 +184,5 @@ namespace OMS.NET.DbClass
} }
return null; return null;
} }
private void AddParameters(MySqlCommand command)
{
foreach (var property in GetProperties(GetType()))
{
//var columnAttr = property.GetCustomAttribute<ColumnAttribute>()!;
command.Parameters.AddWithValue("@" + property.Name, property.GetValue(this));
}
}
private IEnumerable<string> ShowDetail()
{
return GetProperties(GetType()).Select(p => $"{p.Name}={p.GetValue(this)}");
}
private static void PopulateObject(MySqlDataReader reader, BaseObject obj)
{
var type = obj.GetType();
foreach (var property in GetProperties(type))
{
var columnAttr = property.GetCustomAttribute<ColumnAttribute>()!;
var value = reader[columnAttr.ColumnName];
if (value != DBNull.Value)
{
property.SetValue(obj, Convert.ChangeType(value, property.PropertyType));
}
}
}
} }
} }

@ -0,0 +1,74 @@
using System.Reflection;
using MySql.Data.MySqlClient;
using OMS.NET.Common;
namespace OMS.NET.DbClass
{
public class SqlTable
{
public void Test()
{
Console.WriteLine("===========this is a test area=================");
Console.WriteLine(SqlHelper.GetInsertSql(GetType()));
Console.WriteLine(SqlHelper.GetDeleteSql(GetType()));
Console.WriteLine(SqlHelper.GetUpdateSql(GetType()));
Console.WriteLine(SqlHelper.GetSelectSql(GetType()));
Console.WriteLine(SqlHelper.GetSelectSqlWithPrimaryKey(GetType()));
Console.WriteLine("===========this is a test area=================");
}
public virtual void Insert()
{
var type = GetType();
var insertSql = SqlHelper.GetInsertSql(GetType());
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open(); // 确保在执行命令之前打开连接
using var command = new MySqlCommand(insertSql, connection);
AddParameters(command);
Console.WriteLine($"SQL: {command.CommandText}");
foreach (MySqlParameter param in command.Parameters)
{
Console.WriteLine($"Parameter: {param.ParameterName}, Value: {param.Value}");
}
command.ExecuteNonQuery();
Log.Info($"{SqlHelper.GetTableName(type)}数据表插入({string.Join(',', ShowDetail())})");
}
public virtual void Update()
{
var type = GetType();
var updateSql = SqlHelper.GetUpdateSql(GetType());
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open(); // 确保在执行命令之前打开连接
using var command = new MySqlCommand(updateSql, connection);
AddParameters(command);
command.ExecuteNonQuery();
Log.Info($"{SqlHelper.GetTableName(type)}数据表修改({string.Join(',', ShowDetail())})");
}
public virtual void Delete()
{
var type = GetType();
var deleteSql = SqlHelper.GetDeleteSql(GetType());
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open(); // 确保在执行命令之前打开连接
using var command = new MySqlCommand(deleteSql, connection);
AddParameters(command);
command.ExecuteNonQuery();
Log.Info($"{SqlHelper.GetTableName(type)}数据表删除({string.Join(',', ShowDetail())})");
}
private void AddParameters(MySqlCommand command)
{
foreach (var property in SqlHelper.GetProperties(GetType()))
{
command.Parameters.AddWithValue("@" + property.Name, property.GetValue(this));
}
}
private IEnumerable<string> ShowDetail()
{
return SqlHelper.GetProperties(GetType()).Select(p => $"{p.Name}={p.GetValue(this)}");
}
}
}
Loading…
Cancel
Save