.net core 简单介绍:
.net core 是微软公司推出的一个跨平台 框架 他重写了Clr底层 屏蔽window 的依赖,可以运行window ,linux ,max等系统 效率比.net framework 要高出很多。
简单说明下.net core 的目录
下面是我学习的时候 写的增删改查
先预览 下界面
1.控制器
using HomeMediaFileManageSystemUtilts.Sql;
using Microsoft.AspNetCore.Mvc;
using System.Data.SqlClient;
namespace NetCore.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
///
/// 查询
///
///
public IActionResult GetUser()
{
//切换数据的语句
//SqlHelper.SetConStr();
var sql = @"SELECT* FROM(
SELECT RID = ROW_NUMBER() OVER(ORDER BY ID),*FROM STUDENT
) A
WHERE A.RID BETWEEN 1 AND 20 AND A.STATUS=1";
var ds = SqlHelper.ExecuteDataSetText(sql, null);
return Json(ds);
}
///
/// 删除
///
///
///
public string DelUserById(int id) {
var msg = default(string);
var sql = "UPDATE STUDENT SET STATUS=0 WHERE Id=@Id";
SqlParameter[] parameters = new SqlParameter[] {
new SqlParameter("@Id",id)
};
var len=SqlHelper.ExecteNonQueryText(sql, parameters);
if (len > 0)
{
msg = "删除成功";
}
else {
msg = "删除失败";
}
return msg;
}
///
/// 根据Id查找
///
///
///
public IActionResult GetUserById(int id) {
var sql = " SELECT * FROM STUDENT WHERE Id=@Id";
SqlParameter[] parameters = new SqlParameter[] {
new SqlParameter("@Id",id)
};
var ds= SqlHelper.ExecuteDataSetText(sql, parameters);
return Json(ds);
}
///
/// 修改
///
///
///
public string UpdateUserById(int id,string name,string school,int age) {
string msg = string.Empty;
var sql = "UPDATE STUDENT SET Age=@age,Name=@Name,School=@School WHERE ID=@ID";
SqlParameter[] parameters = new SqlParameter[] {
new SqlParameter("@Id",id),
new SqlParameter("@Age",age),
new SqlParameter("@Name",name),
new SqlParameter("@School",school),
};
var len = SqlHelper.ExecteNonQueryText(sql, parameters);
if (len > 0)
{
msg = "修改成功";
}
else
{
msg = "修改失败";
}
return msg;
}
}
}
2.视图
@{
ViewData["Title"] = "Index";
}
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/js/Home.js"></script>
<style>
#table {
display: none;
}
td {
height: 40px;
text-align: center;
}
tr:hover {
background-color: lightseagreen;
}
#mask-kk {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 999;
background: #666;
opacity: 0.5;
filter: alpha(opacity=50)-moz-opacity: 0.5;
display: none;
}
.popup-kk {
position: absolute;
left: 50%;
width: 400px;
height: 300px;
background: #fff;
z-index: 1000;
display: none;
border-radius: 5px;
}
.layoutDiv {
margin-top:20px;
}
.close {
position: absolute;
top: 21px;
right: 20px;
cursor: pointer;
}
</style>
<center>
<h2>.NET Core 增删改查</h2>
<table border="1" cellpadding="0" cellspacing="0" style="width:1200px" id="table">
<tr>
<th>用户编号</th>
<th>用户名</th>
<th>年龄</th>
<th>性别</th>
<th>爱好</th>
<th>学校</th>
<th>身高</th>
<th>创建时间</th>
<th>状态</th>
<th>操作</th>
</tr>
<tbody id="tbody"></tbody>
</table>
</center>
<div id="mask-kk">
</div>
<div class="popup-kk">
@* 弹出层内容 *@
<center>
<input type="hidden" style="width:300px;" id="Id" autocomplete="off" />
<div class="layoutDiv">
<span>用户名</span>
<input type="text" style="width:300px;" id="Name" autocomplete="off" />
</div>
<div class="layoutDiv">
<span>年 龄</span>
<input type="text" style="width:300px;" id="Age" autocomplete="off" />
</div>
<div class="layoutDiv">
<span>学 校</span>
<input type="text" style="width:300px;" id="School" />
</div>
<div class="layoutDiv">
</div>
<button style="width:80px; margin-left:10px;" onclick="UserOptions.Update()">确认</button>
<button style="width:80px; margin-left:10px;" onclick="UserOptions.Reset()">重置</button>
<button style="width:80px; margin-left:10px;" onclick="closeWindow()">关闭</button>
</center>
</div>
3.JS代码
$(function () {
UserOptions.GetUsers();
})
var UserOptions = {
//加载数据源
GetUsers:function(){
$.ajax({
url: '/Home/GetUser',
success: function (data) {
$("#table").show();
var html = "";
for (var i = 0; i < data["table"].length; i++) {
html += "" + data["table"][i]["id"] + " " + data["table"][i]["name"] + " " + data["table"][i]["age"] + " " + data["table"][i]["sex"] + " " + data["table"][i]["hobby"] + " " + data["table"][i]["school"] + " " + data["table"][i]["height"] + " " + data["table"][i]["createTime"] + " " + data["table"][i]["status"] + " | "
}
$("#tbody").html(html)
}
})
},
//修改
Update: function () {
$.ajax({
url: '/Home/UpdateUserById',
data: {
id: $("#Id").val(),
name: $("#Name").val(),
school: $("#School").val(),
age: $("#Age").val(),
},
success: function (data) {
alert(data);
closeWindow();
UserOptions.GetUsers();
}
})
},
//删除
Del: function (obj) {
var id = $(obj).attr("data-id");
$.ajax({
url: '/Home/DelUserById',
data: {
id:id,
},
success: function (data) {
alert(data);
//重新加载数据
UserOptions.GetUsers();
}
})
},
Reset: function () {
$("#Name").val("");
$("#Age").val("");
$("#School").val("");
}
}
//打开
function OpenModelWindow(obj) {
$('#mask-kk').css({
display: 'block',
height: $(document).height()
})
var $Popup = $('.popup-kk');
$Popup.css({
left: ($('body').width() - $Popup.width()) / 2 + 'px',
top: ($(window).height() - $Popup.height()) / 2 + $(window).scrollTop() + 'px',
display: 'block'
})
$("body").css({ overflow: "hidden" });
var id = $(obj).attr("data-id");
$.ajax({
url: '/Home/GetUserById',
data: {
id: id,
},
success: function (data) {
$("#Id").val(data["table"][0]["id"]);
$("#Name").val(data["table"][0]["name"]);
$("#Age").val(data["table"][0]["age"]);
$("#School").val(data["table"][0]["school"]);
}
})
}
//关闭
function closeWindow() {
$('#mask-kk,.popup-kk').css('display', 'none');
$("body").css({ overflow: "" })
}
4.我自定义的文件
{
//自定义配置文件
"ConnectionString": {
"ConStr": "Data Source=.;Initial Catalog=TestDb;Integrated Security=True"
}
}
5.我的配置类
using Microsoft.Extensions.Configuration;
using System.IO;
namespace NetCore.ConfigurationFile
{
///
/// 配置类
///
public class ConnectionString
{
private static readonly object objLock = new object();
private static ConnectionString instance = null;
IConfigurationRoot config = default(IConfigurationRoot);
public ConnectionString()
{
ConfigurationBuilder configuration = new ConfigurationBuilder();
//读取配置文件
config = configuration.SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(file =>
{
file.Path = "/config.json";
file.Optional = false;
file.ReloadOnChange = true;
}).Build();
}
public static ConnectionString GetInstance()
{
if (instance == null)
{
lock (objLock)
{
if (instance == null)
{
instance = new ConnectionString();
}
}
}
return instance;
}
public static string GetConfig(string section,string key)
{
return (string)GetInstance().config.GetSection(section).GetValue(typeof(string), key);
}
}
}
6.贴出我的SQLHelper帮助类
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Data.SqlTypes;
using System.IO;
using NetCore.ConfigurationFile;
namespace HomeMediaFileManageSystemUtilts.Sql
{
///
/// 数据库的通用访问代码 抽象类
/// 不允许实例化,在应用时直接调用即可
///
public abstract class SqlHelper
{
///
/// 数据库连接字符串
///
public static string connectionString = ConnectionString.GetConfig("ConnectionString", "ConStr");
//public static string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DBConn"].ConnectionString;
// Hashtable to store cached parameters
private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
private static string saveFilePath;
///
/// 设置多个数据库连接的字符串
///
///
public static void SetConStr(string section = "ConnectionString", string key = "ConStr")
{
connectionString = ConnectionString.GetConfig(section, key);
}
#region //ExecteNonQuery方法
///
///执行一个不需要返回值的SqlCommand命令,通过指定专用的连接字符串。
/// 使用参数数组形式提供参数列表
///
/// 一个有效的数据库连接字符串
/// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)
/// 存储过程的名字或者 T-SQL 语句
/// 以数组形式提供SqlCommand命令中用到的参数列表
/// 返回一个数值表示此SqlCommand命令执行后影响的行数
public static int ExecteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
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;
}
}
///
///执行一个不需要返回值的SqlCommand命令,通过指定专用的连接字符串。
/// 使用参数数组形式提供参数列表
///
/// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)
/// 存储过程的名字或者 T-SQL 语句
/// 以数组形式提供SqlCommand命令中用到的参数列表
/// 返回一个数值表示此SqlCommand命令执行后影响的行数
public static int ExecteNonQuery(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
return ExecteNonQuery(connectionString, cmdType, cmdText, commandParameters);
}
///
///存储过程专用
///
/// 存储过程的名字
/// 以数组形式提供SqlCommand命令中用到的参数列表
/// 返回一个数值表示此SqlCommand命令执行后影响的行数
public static int ExecteNonQueryProducts(string cmdText, params SqlParameter[] commandParameters)
{
return ExecteNonQuery(CommandType.StoredProcedure, cmdText, commandParameters);
}
///
///Sql语句专用
///
/// T_Sql语句
/// 以数组形式提供SqlCommand命令中用到的参数列表
/// 返回一个数值表示此SqlCommand命令执行后影响的行数
public static int ExecteNonQueryText(string cmdText, params SqlParameter[] commandParameters)
{
return ExecteNonQuery(CommandType.Text, cmdText, commandParameters);
}
#endregion
#region//GetTable方法
///
/// 执行一条返回结果集的SqlCommand,通过一个已经存在的数据库连接
/// 使用参数数组提供参数
///
/// 一个现有的数据库连接
/// SqlCommand命令类型
/// 存储过程的名字或者 T-SQL 语句
/// 以数组形式提供SqlCommand命令中用到的参数列表
/// 返回一个表集合(DataTableCollection)表示查询得到的数据集
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;
}
///
/// 执行一条返回结果集的SqlCommand,通过一个已经存在的数据库连接
/// 使用参数数组提供参数
///
/// SqlCommand命令类型
/// 存储过程的名字或者 T-SQL 语句
/// 以数组形式提供SqlCommand命令中用到的参数列表
/// 返回一个表集合(DataTableCollection)表示查询得到的数据集
public static DataTableCollection GetTable(CommandType cmdTye, string cmdText, SqlParameter[] commandParameters)
{
return GetTable(SqlHelper.connectionString, cmdTye, cmdText, commandParameters);
}
///
/// 存储过程专用
///
/// 存储过程的名字或者 T-SQL 语句
/// 以数组形式提供SqlCommand命令中用到的参数列表
/// 返回一个表集合(DataTableCollection)表示查询得到的数据集
public static DataTableCollection GetTableProducts(string cmdText, SqlParameter[] commandParameters)
{
return GetTable(CommandType.StoredProcedure, cmdText, commandParameters);
}
///
/// Sql语句专用
///
/// T-SQL 语句
/// 以数组形式提供SqlCommand命令中用到的参数列表
/// 返回一个表集合(DataTableCollection)表示查询得到的数据集
public static DataTableCollection GetTableText(string cmdText, SqlParameter[] commandParameters)
{
return GetTable(CommandType.Text, cmdText, commandParameters);
}
#endregion
///
/// 为执行命令准备参数
///
/// SqlCommand 命令
/// 已经存在的数据库连接
/// 数据库事物处理
/// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)
/// Command text,T-SQL语句 例如 Select * from Products
/// 返回带参数的命令
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);
}
}
///
/// Execute a SqlCommand that returns a resultset against the database specified in the connection string
/// using the provided parameters.
///
/// 一个有效的数据库连接字符串
/// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)
/// 存储过程的名字或者 T-SQL 语句
/// 以数组形式提供SqlCommand命令中用到的参数列表
/// A SqlDataReader containing the results
public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
// 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
{
SqlConnection conn = new SqlConnection(connectionString);
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
catch
{
throw;
}
}
#region//ExecuteDataSet方法
///
/// return a dataset
///
/// 一个有效的数据库连接字符串
/// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)
/// 存储过程的名字或者 T-SQL 语句
/// 以数组形式提供SqlCommand命令中用到的参数列表
/// return a dataset
public static DataSet ExecuteDataSet(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = cmd;
da.Fill(ds);
return ds;
}
}
catch
{
throw;
}
}
///
/// 返回一个DataSet
///
/// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)
/// 存储过程的名字或者 T-SQL 语句
/// 以数组形式提供SqlCommand命令中用到的参数列表
/// return a dataset
public static DataSet ExecuteDataSet(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteDataSet(connectionString, cmdType, cmdText, commandParameters);
}
///
/// 返回一个DataSet
///
/// 存储过程的名字
/// 以数组形式提供SqlCommand命令中用到的参数列表
/// return a dataset
public static DataSet ExecuteDataSetProducts(string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteDataSet(connectionString, CommandType.StoredProcedure, cmdText, commandParameters);
}
///
/// 返回一个DataSet
///
/// T-SQL 语句
/// 以数组形式提供SqlCommand命令中用到的参数列表
/// return a dataset
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)
{
SqlCommand cmd = new SqlCommand();
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
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
{
throw;
}
}
#endregion
#region // ExecuteScalar方法
///
/// 返回第一行的第一列
///
/// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)
/// 存储过程的名字或者 T-SQL 语句
/// 以数组形式提供SqlCommand命令中用到的参数列表
/// 返回一个对象
public static object ExecuteScalar(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteScalar(SqlHelper.connectionString, cmdType, cmdText, commandParameters);
}
///
/// 返回第一行的第一列存储过程专用
///
/// 存储过程的名字
/// 以数组形式提供SqlCommand命令中用到的参数列表
/// 返回一个对象
public static object ExecuteScalarProducts(string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteScalar(SqlHelper.connectionString, CommandType.StoredProcedure, cmdText, commandParameters);
}
///
/// 返回第一行的第一列Sql语句专用
///
/// 者 T-SQL 语句
/// 以数组形式提供SqlCommand命令中用到的参数列表
/// 返回一个对象
public static object ExecuteScalarText(string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteScalar(SqlHelper.connectionString, CommandType.Text, cmdText, commandParameters);
}
///
/// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string
/// using the provided parameters.
///
///
/// e.g.:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
///
/// 一个有效的数据库连接字符串
/// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)
/// 存储过程的名字或者 T-SQL 语句
/// 以数组形式提供SqlCommand命令中用到的参数列表
/// An object that should be converted to the expected type using Convert.To{Type}
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;
}
}
///
/// Execute a SqlCommand that returns the first column of the first record against an existing database connection
/// using the provided parameters.
///
///
/// e.g.:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
///
/// 一个有效的数据库连接字符串
/// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)
/// 存储过程的名字或者 T-SQL 语句
/// 以数组形式提供SqlCommand命令中用到的参数列表
/// An object that should be converted to the expected type using Convert.To{Type}
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
///
/// add parameter array to the cache
///
/// Key to the parameter cache
/// an array of SqlParamters to be cached
public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
{
parmCache[cacheKey] = commandParameters;
}
///
/// Retrieve cached parameters
///
/// key used to lookup parameters
/// Cached SqlParamters array
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;
}
///
/// 检查是否存在
///
/// Sql语句
/// 参数
/// bool结果
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;
}
}
}
}