“21天好习惯”第一期-6

本文详细介绍了如何在ASP.NET MVC中通过C#连接SQL Server数据库,并展示了如何优化的实现增删改查操作,包括修复Update方法中的错误,创建、编辑和删除视图,以及重构代码以提高复用性。
摘要由CSDN通过智能技术生成

ASP.NET MVC 连接数据库

利用连接SQL server数据库的代码和SQL语句来在MVC程序中实现数据的增删改查操作

接下来实现改操作


1.Edit页面

在昨天的项目中发生了一点小错误

 原因是这里的SET后面没有空格

PhotoService中的Update方法实现更新数据的功能

public List<Photo> Update(Photo photo)
        {
            string connString = "Data Source=DESKTOP-S1LO8P3\\H;Initial Catalog=PhotoDB;Integrated Security=SSPI;";
            SqlConnection connection = new SqlConnection(connString);

            //string sql = "UPDATE [dbo].[Photo] SET";  //发生语法错误
            string sql = "UPDATE [dbo].[Photo] SET ";
            //sql += "photoFileName='photo.photoFileName',photoShootTime='photo.photoShootTime',photographer=' photo.photographer'";
            //使用上面的语法日期转换会发生错误
            sql += string.Format("photoFileName='{0}',photoShootTime='{1}',photographer='{2}'",photo.photoFileName,photo.photoShootTime,photo.photographer);
            sql += "WHERE photoID=" + photo.photoID;
            sql += "SELECT photoID,photoFileName,photoShootTime,photographer FROM [dbo].[Photo]"; //查找更新后的所有数据

            SqlCommand command = new SqlCommand(sql, connection);
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();

            List<Photo> list = new List<Photo>();
            while (reader.Read())
            {
                Photo p = new Photo()
                {
                    photoID = (int)reader["photoID"],
                    photoFileName = reader["photoFileName"].ToString(),
                    photoShootTime = Convert.ToDateTime(reader["photoShootTime"]),
                    photographer = reader["photographer"].ToString()
                };
                list.Add(p);
            }
            connection.Close(); //关闭数据库连接
            return list;

        }

对应控制器中的Edit操作方法

  // GET: Photo/Edit/5
        public ActionResult Edit(int id)
        {
            Photo photo = service.Find(id);
            return View(photo);
        }

        // POST: Photo/Edit/5
        [HttpPost]
        public ActionResult Edit(Photo photo)
        {
            List<Photo> list = service.Update(photo);
            return View("index",list);
        }

记住要生成对应的Edit模板视图

2.Create页面

 public List<Photo> Add(Photo photo)
        {
            string connString = "Data Source=DESKTOP-S1LO8P3\\H;Initial Catalog=PhotoDB;Integrated Security=SSPI;";
            SqlConnection connection = new SqlConnection(connString);

            string sql = "INSERT INTO [dbo].[Photo] (photoFileName,photoShootTime,photographer) VALUES";
            sql += string.Format("('{0}','{1}','{2}')",photo.photoFileName,photo.photoShootTime,photo.photographer);
            sql += "SELECT photoID,photoFileName,photoShootTime,photographer FROM [dbo].[Photo]";

            SqlCommand command = new SqlCommand(sql, connection);
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();

            List<Photo> list = new List<Photo>();
            while (reader.Read())
            {
                Photo p = new Photo()
                {
                    photoID = (int)reader["photoID"],
                    photoFileName = reader["photoFileName"].ToString(),
                    photoShootTime = Convert.ToDateTime(reader["photoShootTime"]),
                    photographer = reader["photographer"].ToString()
                };
                list.Add(p);
            }
            connection.Close(); //关闭数据库连接
            return list;
        }

从SQL语句后面的代码下来多有重复,可考虑新建一个方法,优化简便代码,但是sql语句的命名需要统一。最后记得添加Create视图页面

3.Delete页面

   public List<Photo> Delete(int id)
        {
            string connString = "Data Source=DESKTOP-S1LO8P3\\H;Initial Catalog=PhotoDB;Integrated Security=SSPI;";
            SqlConnection connection = new SqlConnection(connString);

            string sql = "DELETE FROM [dbo].[Photo] WHERE photoID=" + id;
            sql += "SELECT photoID,photoFileName,photoShootTime,photographer FROM [dbo].[Photo]";

            SqlCommand command = new SqlCommand(sql, connection);
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();

            List<Photo> list = new List<Photo>();
            while (reader.Read())
            {
                Photo p = new Photo()
                {
                    photoID = (int)reader["photoID"],
                    photoFileName = reader["photoFileName"].ToString(),
                    photoShootTime = Convert.ToDateTime(reader["photoShootTime"]),
                    photographer = reader["photographer"].ToString()
                };
                list.Add(p);
            }
            connection.Close(); //关闭数据库连接
            return list;

        }
 public ActionResult Delete(int id)
        {
            Photo photo = service.Find(id);
            return View(photo);
        }

        // POST: Photo/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            List<Photo> list = service.Delete(id);
            return View("index", list);
        }

最后记得添加视图

这就完成了链接数据库的所有的增删改查操作

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Redmonster0923

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值