Skip to content

Commit 014bab5

Browse files
committed
Added "AddTableRowWithResult" and "AddTableRowsWithResult" methods
1 parent 0cc68fb commit 014bab5

File tree

1 file changed

+234
-5
lines changed

1 file changed

+234
-5
lines changed

TLibrary/Helpers/General/DatabaseHelper.cs

Lines changed: 234 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ public static T ConvertToObject<T>(this MySqlDataReader reader) where T : class
172172
try
173173
{
174174
if (!reader.HasRows)
175-
return default;
175+
return null;
176176

177177
T obj = Activator.CreateInstance<T>();
178178

@@ -219,7 +219,7 @@ public static T ConvertToObject<T>(this MySqlDataReader reader) where T : class
219219
{
220220
LoggerHelper.LogException("Error in TLibrary:");
221221
LoggerHelper.LogError(ex);
222-
return default;
222+
return null;
223223
}
224224
}
225225

@@ -234,7 +234,7 @@ public static T ConvertToObject<T>(this DbDataReader reader) where T : class
234234
try
235235
{
236236
if (!reader.HasRows)
237-
return default;
237+
return null;
238238

239239
T obj = Activator.CreateInstance<T>();
240240

@@ -281,7 +281,7 @@ public static T ConvertToObject<T>(this DbDataReader reader) where T : class
281281
{
282282
LoggerHelper.LogException("Error in TLibrary:");
283283
LoggerHelper.LogError(ex);
284-
return default;
284+
return null;
285285
}
286286
}
287287

@@ -908,7 +908,7 @@ public static async Task<bool> AddTableRowAsync<T>(this MySqlConnection connecti
908908
return false;
909909
}
910910
}
911-
911+
912912
/// <summary>
913913
/// Adds a new row to the MySQL database table associated with the type T.
914914
/// The row data is provided as an object of type T.
@@ -1040,7 +1040,236 @@ public static async Task<bool> AddTableRowsAsync<T>(this MySqlConnection connect
10401040
return false;
10411041
}
10421042
}
1043+
1044+
/// <summary>
1045+
/// Adds a new row to the MySQL database table with the specified name and returns the inserted row as an object of type T.
1046+
/// </summary>
1047+
/// <typeparam name="T">The type of object associated with the table.</typeparam>
1048+
/// <param name="connection">The MySqlConnection to the MySQL database.</param>
1049+
/// <param name="tableName">The name of the table to which the row will be added.</param>
1050+
/// <param name="value">The object representing the row data to be added.</param>
1051+
/// <returns>An object of type T representing the inserted row, or default(T) if the insertion fails.</returns>
1052+
public static async Task<T> AddTableRowWithResultAsync<T>(this MySqlConnection connection, string tableName, T value) where T : class
1053+
{
1054+
if (connection == null)
1055+
return null;
1056+
1057+
string commandText = "not_created";
1058+
try
1059+
{
1060+
var schemaType = typeof(T);
1061+
string paramString = string.Empty;
1062+
string keyString = string.Empty;
1063+
1064+
foreach (var prop in schemaType.GetProperties())
1065+
{
1066+
if (prop.GetCustomAttribute<SqlIgnoreAttribute>() != null)
1067+
continue;
1068+
1069+
var memberAttribute = prop.GetCustomAttribute<SqlMemberAttribute>();
1070+
string propName = prop.Name;
1071+
1072+
if (memberAttribute != null)
1073+
{
1074+
if (memberAttribute.ShouldAutoIncrement)
1075+
continue;
1076+
1077+
if (!memberAttribute.ColumnName.IsNullOrEmpty())
1078+
propName = memberAttribute.ColumnName;
1079+
}
1080+
1081+
keyString += $"{propName},";
1082+
bool isNull = false;
1083+
if (prop.GetValue(value) == null)
1084+
{
1085+
isNull = true;
1086+
paramString += "NULL,";
1087+
}
1088+
1089+
1090+
if (!isNull)
1091+
{
1092+
if (prop.PropertyType == typeof(bool) || prop.PropertyType.IsEnum)
1093+
paramString += $"'{Convert.ToInt32(prop.GetValue(value))}',";
1094+
else if (prop.PropertyType == typeof(DateTime))
1095+
paramString += $"'{(DateTime)prop.GetValue(value):yyyy-MM-dd HH:mm:ss.fff}',";
1096+
else if (prop.PropertyType == typeof(string))
1097+
paramString += $"'{ConvertIllegalCharsToSql((string)prop.GetValue(value))}',";
1098+
else
1099+
paramString += $"'{prop.GetValue(value)}',";
1100+
}
1101+
}
1102+
1103+
paramString = paramString.Remove(paramString.LastIndexOf(','), 1);
1104+
keyString = keyString.Remove(keyString.LastIndexOf(','), 1);
1105+
1106+
await connection.OpenSafeAsync();
1107+
T result = null;
1108+
using (var command = connection.CreateCommand())
1109+
{
1110+
command.CommandText = $"INSERT INTO {tableName} ({keyString}) VALUES({paramString});";
1111+
commandText = command.CommandText;
1112+
1113+
using (var reader = await command.ExecuteReaderAsync())
1114+
{
1115+
if (await reader.ReadAsync())
1116+
{
1117+
result = reader.ConvertToObject<T>();
1118+
}
1119+
}
1120+
}
1121+
await connection.CloseAsync();
1122+
return result;
1123+
}
1124+
catch (Exception ex)
1125+
{
1126+
LoggerHelper.LogException("Error in TLibrary:");
1127+
LoggerHelper.LogException($"SQL Command: {commandText}");
1128+
LoggerHelper.LogError(ex);
1129+
if (connection.State != ConnectionState.Closed)
1130+
await connection.CloseAsync();
1131+
return null;
1132+
}
1133+
}
1134+
1135+
/// <summary>
1136+
/// Adds a new row to the MySQL database table associated with the type T and returns the inserted row as an object of type T.
1137+
/// </summary>
1138+
/// <typeparam name="T">The type of object associated with the table.</typeparam>
1139+
/// <param name="connection">The MySqlConnection to the MySQL database.</param>
1140+
/// <param name="value">The object representing the row data to be added.</param>
1141+
/// <returns>An object of type T representing the inserted row, or null if the insertion fails.</returns>
1142+
public static async Task<T> AddTableRowWithResultAsync<T>(this MySqlConnection connection, T value) where T : class
1143+
{
1144+
if (connection == null)
1145+
return null;
1146+
1147+
try
1148+
{
1149+
var schemaType = typeof(T);
1150+
var tableAttribute = schemaType.GetCustomAttribute<SqlNameAttribute>();
1151+
if (tableAttribute == null)
1152+
throw new ArgumentNullException("The given schemaObj does not have SqlNameAttribute.");
1153+
return await AddTableRowWithResultAsync(connection, tableAttribute.Name, value);
1154+
}
1155+
catch (Exception ex)
1156+
{
1157+
LoggerHelper.LogException("Error in TLibrary:");
1158+
LoggerHelper.LogError(ex);
1159+
if (connection.State != ConnectionState.Closed)
1160+
await connection.CloseAsync();
1161+
return null;
1162+
}
1163+
}
1164+
1165+
/// <summary>
1166+
/// Adds multiple new rows to the MySQL database table with the specified name and returns the inserted rows as a list of objects of type T.
1167+
/// </summary>
1168+
/// <typeparam name="T">The type of object associated with the table.</typeparam>
1169+
/// <param name="connection">The MySqlConnection to the MySQL database.</param>
1170+
/// <param name="tableName">The name of the table to which the rows will be added.</param>
1171+
/// <param name="values">The list of objects representing the row data to be added.</param>
1172+
/// <returns>A list of objects of type T representing the inserted rows, or null if the insertion fails.</returns>
1173+
public static async Task<List<T>> AddTableRowsWithResultAsync<T>(this MySqlConnection connection, string tableName, List<T> values) where T : class
1174+
{
1175+
if (connection == null)
1176+
return null;
1177+
1178+
if (values == null)
1179+
return null;
1180+
1181+
if (values.Count == 0)
1182+
return null;
1183+
1184+
string commandText = "not_created";
1185+
try
1186+
{
1187+
var schemaType = typeof(T);
1188+
string paramString = string.Empty;
1189+
string keyString = string.Empty;
1190+
var properties = schemaType.GetProperties();
1191+
1192+
foreach (var value in values)
1193+
{
1194+
paramString += "(";
1195+
foreach (var prop in properties)
1196+
{
1197+
if (prop.GetCustomAttribute<SqlIgnoreAttribute>() != null)
1198+
continue;
1199+
1200+
var memberAttribute = prop.GetCustomAttribute<SqlMemberAttribute>();
1201+
string propName = prop.Name;
1202+
1203+
if (memberAttribute != null)
1204+
{
1205+
if (memberAttribute.ShouldAutoIncrement)
1206+
continue;
1207+
1208+
if (!memberAttribute.ColumnName.IsNullOrEmpty())
1209+
propName = memberAttribute.ColumnName;
1210+
}
1211+
1212+
if (!keyString.Contains(propName))
1213+
keyString += $"{propName},";
1214+
1215+
bool isNull = false;
1216+
if (prop.GetValue(value) == null)
1217+
{
1218+
isNull = true;
1219+
paramString += "NULL,";
1220+
}
1221+
1222+
if (!isNull)
1223+
{
1224+
if (prop.PropertyType == typeof(bool) || prop.PropertyType.IsEnum)
1225+
paramString += $"'{Convert.ToInt32(prop.GetValue(value))}',";
1226+
else if (prop.PropertyType == typeof(DateTime))
1227+
paramString += $"'{(DateTime)prop.GetValue(value):yyyy-MM-dd HH:mm:ss.fff}',";
1228+
else if (prop.PropertyType == typeof(string))
1229+
paramString += $"'{ConvertIllegalCharsToSql((string)prop.GetValue(value))}',";
1230+
else
1231+
paramString += $"'{prop.GetValue(value)}',";
1232+
}
1233+
}
1234+
if (paramString.LastIndexOf(',') > 0)
1235+
paramString = paramString.Remove(paramString.LastIndexOf(','), 1);
1236+
paramString += "),";
1237+
}
1238+
1239+
if (paramString.LastIndexOf(',') > 0)
1240+
paramString = paramString.Remove(paramString.LastIndexOf(','), 1);
1241+
if (keyString.LastIndexOf(',') > 0)
1242+
keyString = keyString.Remove(keyString.LastIndexOf(','), 1);
10431243

1244+
await connection.OpenSafeAsync();
1245+
List<T> result = new List<T>();
1246+
using (var command = connection.CreateCommand())
1247+
{
1248+
command.CommandText = $"INSERT INTO {tableName} ({keyString}) VALUES{paramString};";
1249+
commandText = command.CommandText;
1250+
1251+
using (var reader = await command.ExecuteReaderAsync())
1252+
{
1253+
while (await reader.ReadAsync())
1254+
{
1255+
result.Add(reader.ConvertToObject<T>());
1256+
}
1257+
}
1258+
}
1259+
await connection.CloseAsync();
1260+
return result;
1261+
}
1262+
catch (Exception ex)
1263+
{
1264+
LoggerHelper.LogException("Error in TLibrary:");
1265+
LoggerHelper.LogException($"SQL Command: {commandText}");
1266+
LoggerHelper.LogError(ex);
1267+
if (connection.State != ConnectionState.Closed)
1268+
await connection.CloseAsync();
1269+
return null;
1270+
}
1271+
}
1272+
10441273
/// <summary>
10451274
/// Updates an existing row in the MySQL database table associated with the type T.
10461275
/// The row data is provided as an object of type T, and the update is performed based on the provided WHERE clause and parameters.

0 commit comments

Comments
 (0)