直接建立WEB項目便可;sql
public class Startup { //startup.cs是站點啓動時具體作了哪些事情,主要是開啓了一個mvc服務。 public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddSession(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); //若是不添加將致使樣式文件不能被客戶端加載 app.UseCookiePolicy(); app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); } ); } }
建立一個DB類用於查數據:數據庫
public class DB : DbContext { public DB() { //若是沒有數據庫,自動建立,有了什麼都不幹 Database.EnsureCreated(); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //對於這個上下文重寫此方法以配置要使用的數據庫(和其餘選項)。對於上下文的每一個實例調用此方法建立。 //加載appsetting.json IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json").Build(); string connectionString = configuration["DBSetting:ConnectString"]; optionsBuilder.UseSqlServer(connectionString); base.OnConfiguring(optionsBuilder); } public DbSet<studen> studen { set; get; } public DbSet<xx> xx { set; get; } } //原文:https://blog.csdn.net/weixin_41609327/article/details/80821798
appsettings.json json
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "DBSetting": { "ConnectString": "server=.;database=test_core;uid=sa;pwd=123" }, "AllowedHosts": "*" }
有DB類確定少不了help類數組
/// 此類爲抽象類, /// 不容許實例化,在應用時直接調用便可 /// </summary> // abstract 抽象類標識 public abstract class SqlHelper { //加載appsetting.json static IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json").Build(); /// <summary> /// 數據庫鏈接字符串 /// </summary> private static readonly string connectionString = configuration["DBSetting:ConnectString"]; //獲取DBSetting下的ConnectString值 private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable()); #region//ExecteNonQuery方法 /// <summary> ///執行一個不須要返回值的SqlCommand命令,經過指定專用的鏈接字符串。 /// 使用參數數組形式提供參數列表 /// </summary> /// <param name="connectionString">一個有效的數據庫鏈接字符串</param> /// <param name="cmdType">SqlCommand命令類型 (存儲過程, T-SQL語句, 等等。)</param> /// <param name="cmdText">存儲過程的名字或者 T-SQL 語句</param> /// <param name="commandParameters">以數組形式提供SqlCommand命令中用到的參數列表</param> /// <returns>返回一個數值表示此SqlCommand命令執行後影響的行數</returns> public static int ExecteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { // =執行SQL語句 SqlCommand cmd = new SqlCommand(); using (SqlConnection conn = new SqlConnection(connectionString)) { //經過PrePareCommand方法將參數逐個加入到SqlCommand的參數集合中 PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); int val = cmd.ExecuteNonQuery(); //清空SqlCommand中的參數列表 cmd.Parameters.Clear(); return val; } } /// <summary> ///執行一個不須要返回值的SqlCommand命令,經過指定專用的鏈接字符串。 /// 使用參數數組形式提供參數列表 /// </summary> /// <param name="cmdType">SqlCommand命令類型 (存儲過程, T-SQL語句, 等等。)</param> /// <param name="cmdText">存儲過程的名字或者 T-SQL 語句</param> /// <param name="commandParameters">以數組形式提供SqlCommand命令中用到的參數列表</param> /// <returns>返回一個數值表示此SqlCommand命令執行後影響的行數</returns> public static int ExecteNonQuery(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { return ExecteNonQuery(connectionString, cmdType, cmdText, commandParameters); } /// <summary> ///存儲過程專用 /// </summary> /// <param name="cmdText">存儲過程的名字</param> /// <param name="commandParameters">以數組形式提供SqlCommand命令中用到的參數列表</param> /// <returns>返回一個數值表示此SqlCommand命令執行後影響的行數</returns> public static int ExecteNonQueryProducts(string cmdText, params SqlParameter[] commandParameters) { return ExecteNonQuery(CommandType.StoredProcedure, cmdText, commandParameters); } /// <summary> ///Sql語句專用 /// </summary> /// <param name="cmdText">T_Sql語句</param> /// <param name="commandParameters">以數組形式提供SqlCommand命令中用到的參數列表</param> /// <returns>返回一個數值表示此SqlCommand命令執行後影響的行數</returns> public static int ExecteNonQueryText(string cmdText, params SqlParameter[] commandParameters) { return ExecteNonQuery(CommandType.Text, cmdText, commandParameters); } #endregion #region//GetTable方法 /// <summary> /// 執行一條返回結果集的SqlCommand,經過一個已經存在的數據庫鏈接 /// 使用參數數組提供參數 /// </summary> /// <param name="connecttionString">一個現有的數據庫鏈接</param> /// <param name="cmdTye">SqlCommand命令類型</param> /// <param name="cmdText">存儲過程的名字或者 T-SQL 語句</param> /// <param name="commandParameters">以數組形式提供SqlCommand命令中用到的參數列表</param> /// <returns>返回一個表集合(DataTableCollection)表示查詢獲得的數據集</returns> public static DataTableCollection GetTable(string connecttionString, CommandType cmdTye, string cmdText, SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); DataSet ds = new DataSet(); using (SqlConnection conn = new SqlConnection(connecttionString)) { PrepareCommand(cmd, conn, null, cmdTye, cmdText, commandParameters); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = cmd; adapter.Fill(ds); } DataTableCollection table = ds.Tables; return table; } /// <summary> /// 執行一條返回結果集的SqlCommand,經過一個已經存在的數據庫鏈接 /// 使用參數數組提供參數 /// </summary> /// <param name="cmdTye">SqlCommand命令類型</param> /// <param name="cmdText">存儲過程的名字或者 T-SQL 語句</param> /// <param name="commandParameters">以數組形式提供SqlCommand命令中用到的參數列表</param> /// <returns>返回一個表集合(DataTableCollection)表示查詢獲得的數據集</returns> public static DataTableCollection GetTable(CommandType cmdTye, string cmdText, SqlParameter[] commandParameters) { return GetTable(connectionString, cmdTye, cmdText, commandParameters); } /// <summary> /// 執行存儲過程專用 /// </summary> /// <param name="cmdText">存儲過程的名字或者 T-SQL 語句</param> /// <param name="commandParameters">以數組形式提供SqlCommand命令中用到的參數列表</param> /// <returns>返回一個表集合(DataTableCollection)表示查詢獲得的數據集</returns> public static DataTableCollection GetTableProducts(string cmdText, SqlParameter[] commandParameters) { return GetTable(CommandType.StoredProcedure, cmdText, commandParameters); } /// <summary> /// 執行Sql語句專用 /// </summary> /// <param name="cmdText"> T-SQL 語句</param> /// <param name="commandParameters">以數組形式提供SqlCommand命令中用到的參數列表</param> /// <returns>返回一個表集合(DataTableCollection)表示查詢獲得的數據集</returns> public static DataTableCollection GetTableText(string cmdText, SqlParameter[] commandParameters) { return GetTable(CommandType.Text, cmdText, commandParameters); } #endregion /// <summary> /// 爲執行命令準備參數 /// </summary> /// <param name="cmd">SqlCommand 命令</param> /// <param name="conn">已經存在的數據庫鏈接</param> /// <param name="trans">數據庫事物處理</param> /// <param name="cmdType">SqlCommand命令類型 (存儲過程, T-SQL語句, 等等。)</param> /// <param name="cmdText">Command text,T-SQL語句 例如 Select * from Products</param> /// <param name="cmdParms">返回帶參數的命令</param> private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms) { //判斷數據庫鏈接狀態 if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; //判斷是否須要事物處理 if (trans != null) cmd.Transaction = trans; cmd.CommandType = cmdType; if (cmdParms != null) { foreach (SqlParameter parm in cmdParms) cmd.Parameters.Add(parm); } } /// <summary> /// Execute a SqlCommand that returns a resultset against the database specified in the connection string /// using the provided parameters. /// </summary> /// <param name="connectionString">一個有效的數據庫鏈接字符串</param> /// <param name="cmdType">SqlCommand命令類型 (存儲過程, T-SQL語句, 等等。)</param> /// <param name="cmdText">存儲過程的名字或者 T-SQL 語句</param> /// <param name="commandParameters">以數組形式提供SqlCommand命令中用到的參數列表</param> /// <returns>A SqlDataReader containing the results</returns> public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); SqlConnection conn = new SqlConnection(connectionString); // we use a try/catch here because if the method throws an exception we want to // close the connection throw code, because no datareader will exist, hence the // commandBehaviour.CloseConnection will not work try { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return rdr; } catch { conn.Close(); throw; } } #region//ExecuteDataSet方法 /// <summary> /// return a dataset /// </summary> /// <param name="connectionString">一個有效的數據庫鏈接字符串</param> /// <param name="cmdType">SqlCommand命令類型 (存儲過程, T-SQL語句, 等等。)</param> /// <param name="cmdText">存儲過程的名字或者 T-SQL 語句</param> /// <param name="commandParameters">以數組形式提供SqlCommand命令中用到的參數列表</param> /// <returns>return a dataset</returns> public static DataSet ExecuteDataSet(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlConnection conn = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(); try { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); SqlDataAdapter da = new SqlDataAdapter(); DataSet ds = new DataSet(); da.SelectCommand = cmd; da.Fill(ds); return ds; } catch { conn.Close(); throw; } } /// <summary> /// 返回一個DataSet /// </summary> /// <param name="cmdType">SqlCommand命令類型 (存儲過程, T-SQL語句, 等等。)</param> /// <param name="cmdText">存儲過程的名字或者 T-SQL 語句</param> /// <param name="commandParameters">以數組形式提供SqlCommand命令中用到的參數列表</param> /// <returns>return a dataset</returns> public static DataSet ExecuteDataSet(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { return ExecuteDataSet(connectionString, cmdType, cmdText, commandParameters); } /// <summary> /// 返回一個DataSet /// </summary> /// <param name="cmdText">存儲過程的名字</param> /// <param name="commandParameters">以數組形式提供SqlCommand命令中用到的參數列表</param> /// <returns>return a dataset</returns> public static DataSet ExecuteDataSetProducts(string cmdText, params SqlParameter[] commandParameters) { return ExecuteDataSet(connectionString, CommandType.StoredProcedure, cmdText, commandParameters); } /// <summary> /// 返回一個DataSet /// </summary> /// <param name="cmdText">T-SQL 語句</param> /// <param name="commandParameters">以數組形式提供SqlCommand命令中用到的參數列表</param> /// <returns>return a dataset</returns> public static DataSet ExecuteDataSetText(string cmdText, params SqlParameter[] commandParameters) { return ExecuteDataSet(connectionString, CommandType.Text, cmdText, commandParameters); } public static DataView ExecuteDataSet(string connectionString, string sortExpression, string direction, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlConnection conn = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(); try { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); SqlDataAdapter da = new SqlDataAdapter(); DataSet ds = new DataSet(); da.SelectCommand = cmd; da.Fill(ds); DataView dv = ds.Tables[0].DefaultView; dv.Sort = sortExpression + " " + direction; return dv; } catch { conn.Close(); throw; } } #endregion #region // ExecuteScalar方法 /// <summary> /// 返回第一行的第一列 /// </summary> /// <param name="cmdType">SqlCommand命令類型 (存儲過程, T-SQL語句, 等等。)</param> /// <param name="cmdText">存儲過程的名字或者 T-SQL 語句</param> /// <param name="commandParameters">以數組形式提供SqlCommand命令中用到的參數列表</param> /// <returns>返回一個對象</returns> public static object ExecuteScalar(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { return ExecuteScalar(SqlHelper.connectionString, cmdType, cmdText, commandParameters); } /// <summary> /// 返回第一行的第一列存儲過程專用 /// </summary> /// <param name="cmdText">存儲過程的名字</param> /// <param name="commandParameters">以數組形式提供SqlCommand命令中用到的參數列表</param> /// <returns>返回一個對象</returns> public static object ExecuteScalarProducts(string cmdText, params SqlParameter[] commandParameters) { return ExecuteScalar(SqlHelper.connectionString, CommandType.StoredProcedure, cmdText, commandParameters); } /// <summary> /// 返回第一行的第一列Sql語句專用 /// </summary> /// <param name="cmdText">者 T-SQL 語句</param> /// <param name="commandParameters">以數組形式提供SqlCommand命令中用到的參數列表</param> /// <returns>返回一個對象</returns> public static object ExecuteScalarText(string cmdText, params SqlParameter[] commandParameters) { return ExecuteScalar(SqlHelper.connectionString, CommandType.Text, cmdText, commandParameters); } /// <summary> /// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">一個有效的數據庫鏈接字符串</param> /// <param name="cmdType">SqlCommand命令類型 (存儲過程, T-SQL語句, 等等。)</param> /// <param name="cmdText">存儲過程的名字或者 T-SQL 語句</param> /// <param name="commandParameters">以數組形式提供SqlCommand命令中用到的參數列表</param> /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns> public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); using (SqlConnection connection = new SqlConnection(connectionString)) { PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } } /// <summary> /// Execute a SqlCommand that returns the first column of the first record against an existing database connection /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">一個有效的數據庫鏈接字符串</param> /// <param name="cmdType">SqlCommand命令類型 (存儲過程, T-SQL語句, 等等。)</param> /// <param name="cmdText">存儲過程的名字或者 T-SQL 語句</param> /// <param name="commandParameters">以數組形式提供SqlCommand命令中用到的參數列表</param> /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns> public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } #endregion /// <summary> /// add parameter array to the cache /// </summary> /// <param name="cacheKey">Key to the parameter cache</param> /// <param name="cmdParms">an array of SqlParamters to be cached</param> public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters) { parmCache[cacheKey] = commandParameters; } /// <summary> /// Retrieve cached parameters /// </summary> /// <param name="cacheKey">key used to lookup parameters</param> /// <returns>Cached SqlParamters array</returns> public static SqlParameter[] GetCachedParameters(string cacheKey) { SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey]; if (cachedParms == null) return null; SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length]; for (int i = 0, j = cachedParms.Length; i < j; i++) clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone(); return clonedParms; } /// <summary> /// 檢查是否存在 /// </summary> /// <param name="strSql">Sql語句</param> /// <returns>bool結果</returns> public static bool Exists(string strSql) { int cmdresult = Convert.ToInt32(ExecuteScalar(connectionString, CommandType.Text, strSql, null)); if (cmdresult == 0) { return false; } else { return true; } } /// <summary> /// 檢查是否存在 /// </summary> /// <param name="strSql">Sql語句</param> /// <param name="cmdParms">參數</param> /// <returns>bool結果</returns> public static bool Exists(string strSql, params SqlParameter[] cmdParms) { int cmdresult = Convert.ToInt32(ExecuteScalar(connectionString, CommandType.Text, strSql, cmdParms)); if (cmdresult == 0) { return false; } else { return true; } } //原文:https://blog.csdn.net/weixin_41609327/article/details/80786764 }
public DataTable GetStuden() { string sql = "select * from studen;"; var data = SqlHelper.GetTable(CommandType.Text,sql,new SqlParameter[] { }); return data[0]; }
一個保存類:cookie
public static class save { public static void JsonWrite(string configpath,string str,out string name,out string filename) { //string configpath = System.AppDomain.CurrentDomain.BaseDirectory + "/json/"; configpath = configpath + "/json/"; if (!Directory.Exists(configpath))//若是目錄不存在就建立 { Directory.CreateDirectory(configpath); } filename = configpath + "/"; name = "Json_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_ffff") + ".json";//用日期對文件命名; filename = filename + name; // 一個 文件的 絕對路徑 out 出去 給使用 //建立或打開文件, AppendText 向文件末尾追加記錄 StreamWriter mySw = File.AppendText(filename); // 查找是否有該路徑的文件 並打開 string a = str; mySw.WriteLine(a); // 寫入某數據 //關閉文件 mySw.Close(); // 關閉寫入流 } }
到控制器下載了。mvc
public IActionResult Json() { using (var db = new DB()) { List<studen> list = db.studen.GroupBy(b=>new { b.Id,b.Name }).Select(b => new studen { Id = b.Key.Id, Name = b.Key.Name }).ToList(); db.studen.ToList(); var xx = db.xx.GroupBy(x => new { x.id }).Select(v => new xx { id=v.Key.id, name= v.Sum(x => x.name) }).ToList(); string json = "["; foreach (var item in list) { json += "{\"id\":\""+item.Id+"\",\"name\":\""+item.Name+"\" },"; } json = json.Substring(0, json.Length - 1); //刪除最後一個逗號, json += "]"; //string root = Directory.GetParent(AppContext.BaseDirectory).Parent.Parent.Parent.FullName; //Parent退到上個目錄 string contentRootPath = _hostingEnvironment.ContentRootPath; // .net core獲取基目錄的用法 string name; // out 出來的是路徑加上json文件名 string file; // 絕對路徑 save.JsonWrite(contentRootPath, json.ToString(),out name, out file); //寫入文件 並保存 HttpContext.Session.SetString("file",file); // core 的 Session 就得這麼用 還得using Microsoft.AspNetCore.Http; // 讀取某json文件 string str = ""; using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) // 獲取文件流 { using (StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("utf-8"))) // 讀取文件流 { str = sr.ReadToEnd().ToString(); // 獲取 文件的 所有 轉 字符串 sr.Close(); } fs.Close(); } } // new filestram 須文件的絕對路徑 獲取文件流 輸入出的文件格式 輸出的文件名稱 return File(new FileStream(HttpContext.Session.GetString("file"), FileMode.Open), "application/octet-stream", $"導出測試{DateTime.Now.ToString("yyyy年MM月dd日HH點mm分ss秒")}.json"); if (System.IO.File.Exists("文件的絕對路徑")) { //刪除文件 System.IO.File.Delete("文件的絕對路徑"); } } //public IActionResult download() //{ // return File(new FileStream(HttpContext.Session.GetString("file"), FileMode.Open), "application/octet-stream", $"導出測試{DateTime.Now.ToString("yyyyMMddHHmmss")}.json"); //}