StudentManager/StudentManager/Common/SQLHelper.cs
2024-09-24 19:00:10 +08:00

391 lines
12 KiB
C#

using DryIoc.ImTools;
using Google.Protobuf.WellKnownTypes;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using StudentManager.Data;
using System.Diagnostics;
using System;
using Enum = System.Enum;
using System.Security.Cryptography;
namespace StudentManager.Common
{
static class Tables
{
static public string UserTable { get; } = "users";
static public string QuesTable { get; } = "questions";
static public string UQTable { get; } = "user_data";
static public string CQTable { get; } = "curson_questions";
}
public static class SQLMapping
{
public static void Mapping<T>(MySqlDataReader reader)
{
typeof(T).GetProperties().ForEach(x => { Debug.WriteLine(x.Name.ToLower()); });
}
public static void Mapping<T>(T data, MySqlDataReader reader)
{
if (typeof(T) == typeof(StudentData))
{
(data as StudentData).UID = (long)reader[0];
(data as StudentData).Name = reader[1].ToString();
(data as StudentData).Gender = reader[2].ToString();
(data as StudentData).Contact = reader[3].ToString();
(data as StudentData).Address = reader[4].ToString();
(data as StudentData).Grade = (byte)reader[5];
(data as StudentData).TotalsQuestions = (UInt16)reader[6];
(data as StudentData).CorrectionCount = (UInt16)reader[7];
(data as StudentData).CurronHomeWorkIndex = (uint)reader[8];
(data as StudentData).Password = reader[9].ToString();
(data as StudentData).Birthdate = (DateTime)reader[10];
(data as StudentData).HWQTotalCount = (uint)reader[11];
(data as StudentData).HWQTotalErrorCount = (uint)reader[12];
}
else if (typeof(T) == typeof(QuestionData))
{
DifficultyLevel dLevel = DifficultyLevel.easy;
QStatus qStatus = QStatus.published;
QType qType = QType.;
(data as QuestionData).Id = (int)reader[0];
Enum.TryParse(reader[1].ToString(), true, out qType);
(data as QuestionData).Type = qType;
(data as QuestionData).Stem = reader[2].ToString();
(data as QuestionData).Answer = reader[3].ToString();
Enum.TryParse(reader[4].ToString(), true, out dLevel);
(data as QuestionData).DifficultyLevel = dLevel;
(data as QuestionData).Category = reader[5].ToString();
(data as QuestionData).Tags = reader[6].ToString();
(data as QuestionData).Source = reader[7].ToString();
(data as QuestionData).Lesson = (uint)reader[8];
Enum.TryParse(reader[9].ToString(), true, out qStatus);
(data as QuestionData).Status = qStatus;
}
else if (typeof(T) == typeof(CursonQuestionsData))
{
(data as CursonQuestionsData).UID = (int)reader[0];
(data as CursonQuestionsData).ProblemIDS = string.IsNullOrEmpty(reader[1].ToString()) ? Array.Empty<int>() : JsonConvert.DeserializeObject<int[]>(reader[1].ToString());
(data as CursonQuestionsData).CorrectIDS = string.IsNullOrEmpty(reader[2].ToString()) ? Array.Empty<int>() : JsonConvert.DeserializeObject<int[]>(reader[2].ToString());
(data as CursonQuestionsData).Lesson = (uint)reader[3];
(data as CursonQuestionsData).Status = (byte)reader[4];
(data as CursonQuestionsData).DateTime = (DateTime)reader[5];
(data as CursonQuestionsData).TotalCount = (data as CursonQuestionsData).ProblemIDS.Length;
(data as CursonQuestionsData).CorrectCount = (data as CursonQuestionsData).CorrectIDS.Length;
}
else if (typeof(T) == typeof(UserQuestionData))
{
(data as UserQuestionData).PID = (int)reader[1];
(data as UserQuestionData).ErrorCount = (byte)reader[2];
(data as UserQuestionData).CorrectCount = (byte)reader[3];
(data as UserQuestionData).Status = (byte)reader[4] == 1;
}
//for (int i = 0; i < reader.FieldCount; ++i)
//{
// data?.GetType().GetProperties().ForEach(x => { x.SetValue(reader[i].GetType(), reader[i]); });
//}
}
}
struct userTable
{
}
public static class SQLHelper
{
private static Dictionary<System.Type, string> TypeMap = new Dictionary<System.Type, string>
{
{ typeof(QuestionData), "questions" },
{ typeof(CursonQuestionsData), "curson_questions" },
{ typeof(StudentData), "users" },
{ typeof(UserQuestionData), "user_data" },
};
static string config = "server=8.137.125.29;port=3306;user=StudentManager;password=wangxin55;database=studentmanager";
static MySqlConnection connection = null;
static MySqlCommand cmd = null;
// update ** set ** = '**',... where ** = **;
// insert into ** values('**','**'...);
// delete from ** where ** = **;
public static List<T> Query<T>(long id = 9999999, params string[] queryParams) where T : IDataCommon, new()
{
string tableName = string.Empty;
TypeMap.TryGetValue(typeof(T), out tableName);
connection = new MySqlConnection(config);
List<T> result = new List<T>();
string idName = typeof(T) == typeof(StudentData) ? "user_id" : typeof(T) == typeof(QuestionData) ? "problem_id" : "user_id";
try
{
connection.Open();
string queryStr = "";
if (queryParams.Length > 0)
{
string filedList = string.Join(",", queryParams);
queryStr = $"select {filedList} from {tableName};";
if (id != 9999999)
queryStr = $@"select {filedList} from {tableName} WHERE {idName} = {id};";
}
else
{
queryStr = $"select * from {tableName};";
if (id != 9999999)
queryStr = $@"select * from {tableName} WHERE {idName} = {id};";
}
cmd = new MySqlCommand(queryStr, connection);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
T row = new T();
SQLMapping.Mapping(row, reader);
result.Add(row);
}
return result;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
public static List<T> UnionQuery<T>(int id = 9999999, string tableName = "questions", string otherTable = "user_data") where T : IDataCommon, new()
{
connection = new MySqlConnection(config);
List<T> result = new List<T>();
try
{
connection = new MySqlConnection(config);
string queryStr = "";
if (id == 9999999)
queryStr = $@"SELECT u.user_id, q.* FROM {otherTable} u JOIN {tableName} q ON u.problem_id = q.problem_id";
else
queryStr = $@"SELECT q.* FROM {tableName} q JOIN {otherTable} u ON q.problem_id = u.problem_id WHERE u.user_id = {id}";
cmd = new MySqlCommand(queryStr, connection);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
T row = new T();
SQLMapping.Mapping(row, reader);
result.Add(row);
}
return result;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
public static void Add<T>(T value)
{
connection = new MySqlConnection(config);
try
{
string stableName = string.Empty;
TypeMap.TryGetValue(typeof(T), out stableName);
connection.Open();
if (typeof(T) == typeof(QuestionData))
{
var ques = value as QuestionData;
string sql = $"INSERT INTO {stableName} " +
$"(problem_id, problem_type, problem_stem, problem_answer, difficulty_level, category, tags, source, lesson, status) " +
$"VALUES (@Id, @Type, @Stem, @Answer, @DifficultyLevel, @Category, @Tags, @Source, @Lesson, @Status)";
MySqlCommand cmd = new MySqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@Id", ques.Id);
cmd.Parameters.AddWithValue("@Type", ques.Type.ToString());
cmd.Parameters.AddWithValue("@Stem", ques.Stem);
cmd.Parameters.AddWithValue("@Answer", ques.Answer);
cmd.Parameters.AddWithValue("@DifficultyLevel", ques.DifficultyLevel.ToString());
cmd.Parameters.AddWithValue("@Category", ques.Category);
cmd.Parameters.AddWithValue("@Tags", ques.Tags);
cmd.Parameters.AddWithValue("@Source", ques.Source);
cmd.Parameters.AddWithValue("@Lesson", ques.Lesson);
cmd.Parameters.AddWithValue("@Status", ques.Status.ToString());
cmd.ExecuteNonQuery();
cmd.Dispose();
}
//string sql = $"insert into {stableName}"
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
//cmd.Dispose();
connection.Close();
}
}
internal static void UpdateErrorSet(long UID, int PID, bool status)
{
using (MySqlConnection connection = new MySqlConnection(config))
{
try
{
connection.Open();
// 检查记录是否存在
string checkQuery = "SELECT COUNT(*) FROM user_data WHERE user_id = @user_id AND problem_id = @problem_id";
using (MySqlCommand checkCmd = new MySqlCommand(checkQuery, connection))
{
checkCmd.Parameters.AddWithValue("@user_id", UID);
checkCmd.Parameters.AddWithValue("@problem_id", PID);
int recordCount = Convert.ToInt32(checkCmd.ExecuteScalar());
if (recordCount > 0)
{
// 记录存在,执行更新操作
string updateQuery = "UPDATE user_data SET status = @status WHERE user_id = @user_id AND problem_id = @problem_id";
using (MySqlCommand updateCmd = new MySqlCommand(updateQuery, connection))
{
updateCmd.Parameters.AddWithValue("@user_id", UID);
updateCmd.Parameters.AddWithValue("@problem_id", PID);
updateCmd.Parameters.AddWithValue("@status", status);
updateCmd.ExecuteNonQuery();
}
}
else
{
if (status == false)
{
string updateQuery = $"INSERT INTO user_data (user_id, problem_id) VALUES (@user_id, @problem_id)";
using (MySqlCommand updateCmd = new MySqlCommand(updateQuery, connection))
{
updateCmd.Parameters.AddWithValue("@user_id", UID);
updateCmd.Parameters.AddWithValue("@problem_id", PID);
updateCmd.ExecuteNonQuery();
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
connection.Close();
}
}
}
internal static void UpdateHomework(long UID, uint lesson, string totalArray, string correctArray, DateTime dateTime, bool status)
{
using (MySqlConnection connection = new MySqlConnection(config))
{
try
{
connection.Open();
string updateQuery = "UPDATE curson_questions SET status = @status, problem_ids = @problem_ids, " +
"correct_ids = @correct_ids, update_time = @update_time WHERE user_id = @user_id AND lesson = @lesson";
using (MySqlCommand updateCmd = new MySqlCommand(updateQuery, connection))
{
updateCmd.Parameters.AddWithValue("@user_id", UID);
updateCmd.Parameters.AddWithValue("@lesson", lesson);
updateCmd.Parameters.AddWithValue("@status", status);
updateCmd.Parameters.AddWithValue("@problem_ids", totalArray);
updateCmd.Parameters.AddWithValue("@correct_ids", correctArray);
updateCmd.Parameters.AddWithValue("@update_time", dateTime);
updateCmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
connection.Close();
}
}
}
internal static void AddHomework(CursonQuestionsData homeWork)
{
using (MySqlConnection connection = new MySqlConnection(config))
{
try
{
connection.Open();
string updateQuery = "insert into curson_questions (user_id, problem_ids, correct_ids, lesson, status, update_time)" +
"values (@user_id, @problem_ids, @correct_ids, @lesson, @status, @update_time)";
using (MySqlCommand updateCmd = new MySqlCommand(updateQuery, connection))
{
updateCmd.Parameters.AddWithValue("@user_id", homeWork.UID);
updateCmd.Parameters.AddWithValue("@problem_ids", JsonConvert.SerializeObject(homeWork.ProblemIDS));
updateCmd.Parameters.AddWithValue("@correct_ids", JsonConvert.SerializeObject(homeWork.CorrectIDS));
updateCmd.Parameters.AddWithValue("@lesson", homeWork.Lesson);
updateCmd.Parameters.AddWithValue("@status", homeWork.Status);
updateCmd.Parameters.AddWithValue("@update_time", homeWork.DateTime);
updateCmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
}
finally
{
connection.Close();
}
}
}
}
}