"ASP.NET MVC与Sql Server交互, 插入数据"中,在Controller中拼接sql语句。比如:

_db.InsertData("insert into Product(Name,quantity,Price) values('"+productVm.Name+"','"+productVm.Quantity+"','"+productVm.Price+"')");

在某些场景中需要把数据放在字典集合中,再插入到数据库。类似如下:

_db.InsertDataByDic("表名", 字典集合);

这样有更好的可读性。字典集合的键是表的字段们。

于是,可以把相对复杂的sql语句拼接放在了帮助类中。在帮助类中增加一个InsertDataByDic方法,该方法遍历字典集合拼接sql语句。

     public class SqlDB
    {
        protected SqlConnection conn;

        //打开连接
        public bool OpenConnection()
        {
            conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
            try
            {
                bool result = true;
                if (conn.State.ToString() != "Open")
                {
                    conn.Open();
                }
                return result;
            }
            catch (SqlException ex)
            {
                return false;
            }
        }

        //关闭连接
        public bool CloseConnection()
        {
            try
            {
                conn.Close();
                return true;
            }
            catch (Exception ex)
            {

                return false;
            }
        }

        //插入数据
        public int InsertData(string sql)
        {
            int lastId = 0;
            //string query = sql + ";SELECT @@Identity;";
            try
            {
                if(conn.State.ToString()=="Open")
                {
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    //cmd.ExecuteNonQuery();
                    lastId = ToInt(cmd.ExecuteScalar());//返回第一行的第一列
                }
                return ToInt(lastId);
            }
            catch (Exception ex)
            {

                return 0;
            }
        }

        //转换成整型
        private int ToInt(object o)
        {
            try
            {
                return int.Parse(o.ToString());
            }
            catch (Exception ex)
            {

                return 0;
            }
        }

        //插入字典数据
        public int InsertDataByDic(string tableName, Dictionary<string,string> dics)
        {
            int lastId = 0;
            string keyStr = string.Empty;//拼接键
            string valStr = string.Empty;//拼接变量
            int index = 0;//索引
            try
            {
                foreach (KeyValuePair<string, string> item in dics)
                {
                    index++;
                    //第一次拼接前面逗号
                    keyStr += (index != 1 ? "," : "") + "[" + item.Key + "]";
                    valStr += (index != 1 ? "," : "") + "@" + item.Key;
                }

                //拼接sql语句
                string query = "insert into " + tableName + "(" + keyStr + ") values (" + valStr + ");SELECT @@Identity;";
                if (conn.State.ToString() == "Open")
                {
                    SqlCommand cmd = new SqlCommand(query, conn);
                    foreach (KeyValuePair<string, string> item in dics)
                    {
                        cmd.Parameters.AddWithValue("@" + item.Key, item.Value);
                    }
                    lastId = ToInt(cmd.ExecuteScalar());
                }
                return ToInt(lastId);
            }
            catch (Exception ex)
            {
                return 0;
            }
        }
    }


在TestController中增加2个名称为AddProductByDic的Action方法,把从前端获取到的视图模型中的数据赋值给字典集合。

  public class TestController : Controller
    {

        private SqlDB _db = new SqlDB();
        //
        // GET: /Test/
        public ActionResult Index()
        {
            bool r = _db.OpenConnection();
            if (r)
            {
                return Content("连接成功");
            }
            else
            {
                return Content("连接失败");
            }
        }

        //通过sql语句插入数据
        public ActionResult AddProduct()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AddProduct(ProductVm productVm)
        {
            if(ModelState.IsValid)
            {
                _db.OpenConnection();
                int result = _db.InsertData("insert into Product(Name,quantity,Price) values('"+productVm.Name+"','"+productVm.Quantity+"','"+productVm.Price+"')");
                if(result > 0)
                {
                    ModelState.AddModelError("success", "创建成功");
                }
                else
                {
                    ModelState.AddModelError("error", "创建失败");
                }
                _db.CloseConnection();
                return RedirectToAction("Index");
            }
            else
            {
                return View(productVm);
            }
        }

        //通过字典集合插入数据
        public ActionResult AddProductByDic()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AddProductByDic(ProductVm productVm)
        {
            int i = 0;
            if (ModelState.IsValid)
            {
                _db.OpenConnection();
                Dictionary<string, string> data = new Dictionary<string, string>();
                data["Name"] = productVm.Name;
                data["quantity"] = productVm.Quantity;
                data["Price"] = productVm.Price;
                i = _db.InsertDataByDic("Product", data);
                _db.CloseConnection();

                if(i>0)
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    return View(productVm);
                }
            }
            else
            {
                return View(productVm);
            }
        }
    }


AddProductByDic.cshtml是一个强类型视图。

@model Portal.Models.ProductVm

@{
    ViewBag.Title = "AddProductByDic";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>AddProductByDic</h2>

@using (Html.BeginForm("AddProductByDic", "Test", new { @id = "addForm" }, FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>ProductVm</h4>
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Quantity, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Quantity)
                @Html.ValidationMessageFor(model => model.Quantity)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Price, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Price)
                @Html.ValidationMessageFor(model => model.Price)
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="创建" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>


ASP.NET MVC与Sql Server交互,把字典数据插入数据库的更多相关文章

  1. ASP.NET MVC与Sql Server交互, 插入数据

    在"ASP.NET MVC与Sql Server建立连接"中,与Sql Server建立了连接.本篇实践向Sql Server中插入数据. 在数据库帮助类中增加插入数据的方法. p ...

  2. Incorporating ASP.NET MVC and SQL Server Reporting Services, Part 2

    In the last issue, I introduced you to the basics of incorporating SQL Server Reporting Services int ...

  3. SQL Server中Table字典数据的查询SQL示例代码

    SQL Server中Table字典数据的查询SQL示例代码 前言 在数据库系统原理与设计(第3版)教科书中这样写道: 数据库包含4类数据: 1.用户数据 2.元数据 3.索引 4.应用元数据 其中, ...

  4. Incorporating ASP.NET MVC and SQL Server Reporting Services, Part 1

    Your ASP.NET MVC application needs reports. What do you do? In this article, I will demonstrate how ...

  5. ASP.NET MVC与Sql Server建立连接

    用惯了使用Entity Framework连接数据库,本篇就来体验使用SqlConnection连接数据库. 打开Sql Server 2008,创建数据库,创建如下表: create table P ...

  6. asp.net mvc entityframework sql server 迁移至 mysql方法以及遇到的问题

    背景: 我原来的项目是asp.net mvc5 + entityframework 6.4 for sql server(localdb,sql server),现在需要把数据库切换成mysql,理论 ...

  7. SQL Server 关于 Table 字典数据的查询SQL

    分享一个关于查询SQL Server Table 结构的SQL 语句. T-SQL 如下: SELECT (case when a.colorder=1 then d.name else '' end ...

  8. .NET/ASP.NET/C#/WCF/SQL Server/My SQL/Java/JSP/JDBC/Spring/Spring MVC/PHP/Python/Ruby/Shell/Agile/CSS/HTML/HTTP/Unix/Linux大量PDF书籍/电子书籍下载, Effective Java 下载

    223本电子书籍,囊括了.NET/ASP.NET/C#/WCF/SQL Server/My SQL/Java/JSP/JDBC/Spring/Spring MVC/PHP/Python/Shell/A ...

  9. 通过 Docker Compose 组合 ASP NET Core 和 SQL Server

    目录 Docker Compose 简介 安装 WebApi 项目 创建项目 编写Dockfile Web MVC 项目 创建项目 编写Dockfile 编写 docker-compose.yml文件 ...

随机推荐

  1. python3之模块urllib

    urllib是python内置的HTTP请求库,无需安装即可使用,它包含了4个模块: request:它是最基本的http请求模块,用来模拟发送请求 error:异常处理模块,如果出现错误可以捕获这些 ...

  2. 利用shell找出15分钟内修改的文件

    如果你的文件只是生成不会修改的话,可以这样: find * -mmin -15 2>/dev/null 如果可能修改,则需要这样(先创建一个 15 分之前的时间戳的文件,然后找比这个文件新的文件 ...

  3. 【译】ASP.NET Identity Core 从零开始

    原文出自Rui Figueiredo的博客,原文链接<ASP.NET Identity Core From Scratch> 译者注:这篇博文发布时正值Asp.Net Core 1.1 时 ...

  4. shell中后台进程管理: ps -aux 详解

    常用 查找进程id方法:      ps -aux | grep "jupyter"                杀进程:   kill -9 具体的PID 1.ps命令 要对进 ...

  5. **CI创建类库(创建自己的工具类等)

    创建类库 当我们使用术语"类库"时,我们一般指的是位于libraries 文件夹中的类,它们在wiki的"类库参考"这个板块被讨论.在当前这个话题中,我们将讨论 ...

  6. .NetCore中使用ExceptionLess 添加操作日志

    上一篇文章已经扩展了日志,下面我们在结合下处理操作日志 通常我们想到操作日志 可能想到的参数可能有 模块 方法 参数内容 操作人 操作时间 操作 Ip 下面我们就来结合这些信息添加操作日志 如果要在代 ...

  7. T-SQL语句2

    一.修改表 1.alter table 语句 alter table database_name,table_name,column_name,type_name//database_name指数据库 ...

  8. maven 配置阿里云仓库

    <mirror>     <id>nexus-aliyun</id>     <mirrorOf>*</mirrorOf>     < ...

  9. 下载vc++运行库

    之前下载vc++运行库都是百度,从中关村.当下等软件网站下载,但是最近这些网站涉及到安全问题,所以从官网下载比较合适 微软官网-中文 在搜索中 搜索vc++2010/2015等,搜索结果中找到xxxx ...

  10. 【转载】Java是传值还是传引用

    1. 简单类型是按值传递的 Java 方法的参数是简单类型的时候,是按值传递的 (pass by value).这一点我们可以通过一个简单的例子来说明: /* 例 1 */ /** * @(#) Te ...