调整一下数据库表基类,将一些静态方法抽离出来到sqlhelper类
parent
2771293732
commit
192dbff619
@ -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…
Reference in New Issue