C#通過資料庫語言來查詢資料
阿新 • • 發佈:2020-12-31
public List<object> ExecuteReaderSQL(string sql, List<string> colunmlist = null, Dictionary<string, string> paralist = null, bool specialKeyword = false, bool handleFullText= false) { List<object> list = new List<object>(); List<MySqlParameter> paras = new List<MySqlParameter>(); using (SqlConnection conn = new SqlConnection(ParaUtil.Connectionstring)) { conn.Open(); SqlCommand cmd = new SqlCommand(sql, conn); cmd.CommandTimeout = 600; if (paralist != null && paralist.Count > 0) { foreach (KeyValuePair<string, string> dic in paralist) { cmd.Parameters.Add(new SqlParameter(dic.Key, dic.Value)); } } SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { Dictionary<string, object> row = new Dictionary<string, object>(); foreach (string column in colunmlist) { //這邊做個處理 FullText ,提取文字,去除標籤 if (handleFullText && column.ToLower() == "fulltext") { HtmlToText txt = new HtmlToText(); string value = txt.Convert(dr[column].ToString()).Replace(" ", "").Trim(); row.Add(column, value); } else if (specialKeyword && column.ToLower() == "keyword") { string keywords = dr[column].ToString(); string[] keywordArray = keywords.Split(','); string kdList = ""; foreach (string k in keywordArray) { try { Keyword kd = dbcontext.Keywords.FirstOrDefault(t => t.Title == k); kdList += string.Format("ID:'{0}',title:'{1}'|", kd.ID, kd.Title); } catch (Exception e) { kdList += string.Format("ID:'{0}',title:'{1}'|", ' ', k); } } row.Add(column, kdList); } else { row.Add(column, dr[column]); } } list.Add(row); } dr.Close(); conn.Close(); } return list; }