天天看點

ASP.NET MVC使用ADO.NET連接配接資料庫

深入了解ADO.NET友情連結:http://www.cnblogs.com/liuhaorain/category/352388.html

小白手把手:VS2017  SQL Server 2014

第一步:建立項目,選擇Visual C#--ASP.NET Web Application(.NET Framework),鍵入工程名。确認後選擇MVC模式,确認。

ASP.NET MVC使用ADO.NET連接配接資料庫
此時可看到工程目錄包含Controllers,Modles,Views三層。運作程式即可看到VS自帶的MVC模闆。
ASP.NET MVC使用ADO.NET連接配接資料庫

第二步,建立工程完成後,進行資料庫的連接配接,若還沒有在資料庫建好表,則先行建表,建好後進行以下操作。

點選工具欄的Tools--Connect to Database,填寫你所連接配接的資料庫的Server name,選擇身份驗證,輸入使用者名和密碼,然後選擇所要連接配接的資料庫名稱。

ASP.NET MVC使用ADO.NET連接配接資料庫
1.右鍵Models選擇建立項目,選擇Data--ADO.NET Entity Data Model,然後确認;
ASP.NET MVC使用ADO.NET連接配接資料庫
2.選擇Code First from database,點選Next
ASP.NET MVC使用ADO.NET連接配接資料庫
3.在連接配接處選擇起初我們建立好的連接配接,或者略過起初建立連接配接,在此處選擇建立連接配接。
ASP.NET MVC使用ADO.NET連接配接資料庫
ASP.NET MVC使用ADO.NET連接配接資料庫

選擇Yes,include the sensitive data in the connection string.點選Next,選擇将要使用的資料庫對象,包括“表”、“視圖”、“存儲過程和函數”。點選Finish.

完成後會看到Models檔案夾添加了實體資料模型,Web.config檔案添加了連接配接資料庫配置。

ASP.NET MVC使用ADO.NET連接配接資料庫

<connectionStrings><add name="Joke" connectionString="data source=PA181;user id=sa;password=**;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" /></connectionStrings>

第三步,建立Controller,右鍵Controllers檔案add--Controller,選擇MVC5 Controller with read/write actions點選add,命名是後面Controller不要改動。

生成的controller中包含action:

ASP.NET MVC使用ADO.NET連接配接資料庫
第四步,在controllers檔案中建立DBConnect類,用來進行資料庫的連接配接讀寫操作。

using ADO.NET.test.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace ADO.NET.test.Controllers
{
    public class DB
    {
        protected SqlConnection conn;
        //打開連接配接
        public bool OpenConnection()
        {
            conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Joke"].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 (SqlException ex)
            {
                return false;
            }
        }
        //顯示
        public List<Joke> Select()
        {
            SqlDataReader sdr;
            List<Joke> list = new List<Joke>();
            try
            {
                if (conn.State.ToString() == "Open")
                {
                    SqlCommand cmd = new SqlCommand("Select * from Jokes", conn);
                    sdr = cmd.ExecuteReader();
                    while (sdr.Read())
                    {
                        Joke j = new Joke();
                        System.Diagnostics.Debug.WriteLine("ID:{0}\tcontent:{1}\tbelong:{2}\tstate:{3}\ttime:{4}", sdr["ID"], sdr["Content"], sdr["Belong"], sdr["State"], sdr["AddDate"]);
                        j.ID = Convert.ToInt32(sdr["ID"]);
                        j.Content = sdr["Content"].ToString();
                        j.Belong = sdr["Belong"].ToString();
                        j.State = Convert.ToInt32(sdr["State"]);
                        j.AddDate = Convert.ToDateTime(sdr["AddDate"]);

                        list.Add(j);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Joke details wrong:{0}", e);
            }
            finally
            {
                conn.Close();
            }
            return list;
        }
        //Detail
        public Joke Detail(int? id)
        {
            SqlDataReader sdr;
            Joke j = new Joke();
            System.Diagnostics.Debug.WriteLine("編号:{0}", id);
            string sql = "Select * from Jokes where ID = @ID";
            SqlParameter[] paras = new SqlParameter[]{//參數數組
                  new SqlParameter("@ID",System.Data.SqlDbType.Int)};
            paras[0].Value = id;//綁定ID
            try
            {
                if (conn.State.ToString() == "Open")
                {
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    cmd.Parameters.AddRange(paras);
                    sdr = cmd.ExecuteReader();
                    while (sdr.Read())
                    {

                        System.Diagnostics.Debug.WriteLine("ID:{0}\tcontent:{1}\tbelong:{2}\tstate:{3}\ttime:{4}", sdr["ID"], sdr["Content"], sdr["Belong"], sdr["State"], sdr["AddDate"]);
                        j.ID = Convert.ToInt32(sdr["ID"]);
                        j.Content = sdr["Content"].ToString();
                        j.Belong = sdr["Belong"].ToString();
                        j.State = Convert.ToInt32(sdr["State"]);
                        j.AddDate = Convert.ToDateTime(sdr["AddDate"]);
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Joke select wrong:{0}", e);
            }
            finally
            {
                conn.Close();
            }
            return j;

        }
        //Create
        public void Create(Joke joke)
        {
            //SqlDataReader sdr;
            //string sql = "insert into Jokes(Content,Belong,State,AddDate)values('" + joke.Content + "','" + joke.Belong + "','" + joke.State + "','" + joke.AddDate + "')";
            string sql = "insert into Jokes(Content,Belong,State,AddDate)values(@content,@belong,@state,@time)";
            SqlParameter[] paras = new SqlParameter[]{//參數數組
                  new SqlParameter("@content",System.Data.SqlDbType.VarChar),
                   new SqlParameter("@belong",System.Data.SqlDbType.VarChar),
                   new SqlParameter("@state",System.Data.SqlDbType.Int),
                    new SqlParameter("@time",System.Data.SqlDbType.DateTime)};
            paras[0].Value = joke.Content;//綁定内容
            paras[1].Value = joke.Belong;//綁定署名
            paras[2].Value = joke.State;//綁定狀态
            paras[3].Value = joke.AddDate;//綁定時間
            try
            {
                if (conn.State.ToString() == "Open")
                {
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    cmd.Parameters.AddRange(paras);
                    cmd.ExecuteNonQuery();
                    System.Diagnostics.Debug.WriteLine("插入成功!");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Joke create wrong:{0}", e);
            }
            finally
            {
                conn.Close();
            }
        }
        //Delete
        public int Delete(int? id)
        {
            string sql = "delete from Jokes where ID= @ID";
            SqlParameter[] paras = new SqlParameter[]{//參數數組
                  new SqlParameter("@ID",System.Data.SqlDbType.Int)};
            paras[0].Value = id;//綁定ID
            int i = 0;
            try
            {
                if (conn.State.ToString() == "Open")
                {
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    cmd.Parameters.AddRange(paras);
                    i = cmd.ExecuteNonQuery();
                    System.Diagnostics.Debug.WriteLine("插入成功!");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Joke create wrong:{0}", e);
            }
            finally
            {
                conn.Close();
            }
            return i;
        }
        //update
        public int Update(Joke joke)
        {
            string sql = "update Jokes set Content = @content,Belong = @belong where ID= @ID";
            SqlParameter[] paras = new SqlParameter[]{//參數數組
                  new SqlParameter("@content",System.Data.SqlDbType.VarChar),
                   new SqlParameter("@belong",System.Data.SqlDbType.VarChar),
                   new SqlParameter("@ID",System.Data.SqlDbType.Int)};
            paras[0].Value = joke.Content;//綁定内容
            paras[1].Value = joke.Belong;//綁定署名
            paras[2].Value = joke.ID;//綁定ID
            System.Diagnostics.Debug.WriteLine("SQL語句:{0}", sql);
            int i = 0;
            try
            {
                if (conn.State.ToString() == "Open")
                {
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    cmd.Parameters.AddRange(paras);
                    i = cmd.ExecuteNonQuery();
                    System.Diagnostics.Debug.WriteLine("更新成功!");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Joke update wrong:{0}", e);
            }
            finally
            {
                conn.Close();
            }
            return i;
        }
    }
}      

第五步:在Views--Joke檔案夾下建立對應的Controller傳回顯示頁面。

ASP.NET MVC使用ADO.NET連接配接資料庫

第六步,App_Start--RouteConfig.cs修改路由,使初始頁面指向Joke--Index.cshtml.

ASP.NET MVC使用ADO.NET連接配接資料庫

最後運作結果:

ASP.NET MVC使用ADO.NET連接配接資料庫

繼續閱讀