세 가지 간단한 데이터베이스 연결 데이터 등록 기능에 대한 C # 언어 바인딩 프레임 워크를 사용하여

마이크로 소프트 비주얼 스튜디오의 사용에 많은 사람들이 데이터베이스에 연결하는 방법을 알고 세 개의 프레임을 사용하고, 오늘 우리는 간단한 방문 페이지를 만드는 마이크로 소프트 비주얼 스튜디오를 사용하는 방법을 함께 배울 수 없습니다.

工具:
마이크로 소프트 비주얼 스튜디오 2010
SQL Server Management Studio를

단계 :
1. 첫째, 새로운 빈 솔루션을 만드는
여기에 그림 삽입 설명
세 가지를 설정하기 위해 우리가 필요로하는 솔루션을 마우스 오른쪽 단추로 클릭 2.
여기에 그림 삽입 설명
아키텍처는 세 개의 층으로 나누어 져 있기 때문에 한 가지, 세 가지 층의 설립에주의해야 : 프리젠 테이션 계층 (UI (사용자 인터페이스)), 비즈니스 로직 계층 (BLL (비즈니스 논리 계층)) , 데이터 액세스 계층 (DAL (데이터 액세스 계층) ) 플러스 물리적 라이브러리 (모델) 그래서 우리는 모델, DAL 및 BLL 및 UI 층 도서관 (그림 1) 웹 프로젝트가를 확립 내장되어 있습니다 (그림 2)
여기에 그림 삽입 설명
그림 I
여기에 그림 삽입 설명
그림 II

다음 표는 나중에 전체에게 그것을 구축하는 것입니다! 그 중 1/3은 성공했다! 자신을 위해 박수를 보냅니다!
여기에 그림 삽입 설명
방법 세 가지를 연결하는? 그런 다음에 대한 참조가 있습니다! 마우스 오른쪽 참조, 참조를 추가

참조 관계 :
모델을 참조 할 BLL 및 DAL 필요성
DAL은 모델을 참조 할 필요가;
모델 엔티티가 다른 층을 참조 할 필요가 없습니다,
여기에 그림 삽입 설명
다음 데이터베이스에 연결되어 있고 코드 작업 친구를 실행 -
데이터베이스에서 테이블을 수립는 두 개의 내부 테스트라고 : 그리고 두 개의 데이터 열을 나타낸 바와 같이 첨가
여기에 그림 삽입 설명
여기에 그림 삽입 설명
하여 최종 단계의 코드.

Model层:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Model
{
    public class Class1
    {
        public string username {set;get;}
        public string userpwd { set; get; }
    }
}


Dal层:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace Dal
{
    public class Class1
    {
        public List<Model.Class1> MyList(string where) 
        {
            DataSet ds = DB.ToGetData("select *from Test " + where);
            if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
            {
                Model.Class1 MyClass1 = null;
                List<Model.Class1> MyList = new List<Model.Class1>();
                foreach (DataRow item in ds.Tables[0].Rows)
                {
                    MyClass1 = new Model.Class1();
                    MyClass1.username = item["username"].ToString();
                    MyClass1.userpwd = item["userpwd"].ToString();
                    MyList.Add(MyClass1);

                }
                return MyList;
            }
            else 
            {
                return null;
            }
        }
       
    }
    public class DB 
    {
        static string ConnStr = "Data Source=.;Initial Catalog=调用的数据库名;Persist Security Info=True;User ID=数据库用户名;Password=数据库密码";
       
        public static DataSet ToGetData(string Sql)
        {
            using (SqlConnection Conn = new SqlConnection(ConnStr))
            {
                using (SqlDataAdapter da = new SqlDataAdapter(Sql, Conn))
                {
                    DataSet ds = new DataSet();
                    Conn.Open();
                    da.Fill(ds);
                    da.Dispose();
                    return ds;
                }
            }
        } 
    }
}


Bll层:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Bll
{
    public class Class1
    {
        Dal.Class1 NewDal = new Dal.Class1();
        public List<Model.Class1> Login(string username, string userpwd)
        
        {
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(userpwd))
            {
                return NewDal.MyList(" where username='"+username+"' and userpwd='"+userpwd+"'" );
            }
            else 
            {
                return null;
            }
        }
    }
}

UI层:(Login窗体)
1前端:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="UI.Login" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       用户名:&nbsp <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
       用户密码: <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br /><br /><br />
       &nbsp&nbsp&nbsp <asp:Button ID="Button1" runat="server" Text="登Ì?陆?" 
            onclick="Button1_Click"  />
    </div>
    </form>
</body>
</html>


2.后端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UI
{
    public partial class Login : System.Web.UI.Page
    {
        Bll.Class1 NewBll = new Bll.Class1();
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string username = TextBox1.Text.Trim();
            string userpwd = TextBox2.Text.Trim();
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(userpwd))
            {
                List<Model.Class1> Myuserlist = NewBll.Login(username, userpwd);
                if (Myuserlist != null)
                {
                    Page.ClientScript.RegisterStartupScript(GetType(), "js", "<script>alert('登录成功!');</script>");
                }
                else
                {
                    Page.ClientScript.RegisterStartupScript(GetType(), "js", "<script>alert('用户密或密码不存在!');</script>");
                }
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "js", "<script>alert('请输入所有信息!');</script>");
            }
        }
    }
}

UI 계층에서 입력 박스가 실험의 성공 후에 실행 (F5)을 클릭.

추천

출처blog.csdn.net/weixin_44003632/article/details/86637817