初学ASP.NET

在学校里学的是JAVA,到公司实习的时候要求用C#开发网页,然后就慢慢开始熟悉C#了。

第一天实现登录,查询数据库。

由于我使用的数据库是MYSQL,所以在这之前需要下载引用。

(1)首先下载https://dev.mysql.com/downloads/connector/net/ 

(2)安装完成后 在VS2017中添加引用

(3)添加引用 选择Mysql.Data.dll

1.前台代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="Demo.login" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server" method="post">
        <div>
            用户名:<asp:TextBox ID="account" runat="server"></asp:TextBox><br />
            密码:<asp:TextBox ID="password" TextMode="Password" runat="server"></asp:TextBox><br />
            <asp:Button ID="submit" runat="server"  Text="登陆"/>
            <asp:Label ID="label1" runat="server"></asp:Label>
        </div>
    
    </form>
</body>
</html>

2.后台cs代码

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Demo
{
    public partial class login : System.Web.UI.Page
    {
        Operation op = new Operation();//构造数据库连接对象
        protected void Page_Load(object sender, EventArgs e)//个人理解:打开网页时最先加载事件。
        {
            submit.Click += Submit_Click;
        }

        void Submit_Click(object sender, EventArgs e)//按钮点击事件,点击登录就会去数据库查询。
        {
            bool Has = op.Login(account.Text, password.Text);
            if (Has)
            {
                Response.Redirect("WebForm1.aspx?account="+account.Text);
            }
            else
            {
                label1.Text = "fail";
            }
        }
    }
    public class Operation{//数据库连接对象
        MySqlConnection conn=null;
        MySqlCommand cmd = null;
        public Operation()
        {
            conn = new MySqlConnection("Data Source=localhost;User ID=root;Password=123;Database=asptest;SslMode=none");//依次为数据库地址,账号,密码,数据库名  
            cmd = conn.CreateCommand();                                                               //SSLmode这个如果不加会报错 个人的理解是C#不支持的SSL连接
            
        }
        public bool Login(string account,string password)//查询数据库,数据核对
        {
            cmd.CommandText = "select * from user where account=@account and password=@password";
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@account", account);
            cmd.Parameters.Add("@password", password);
            conn.Open();
            MySqlDataReader dr = cmd.ExecuteReader();
            bool has=dr.HasRows;
            return has;
        }
        }
}

猜你喜欢

转载自www.cnblogs.com/luoyijian/p/9243536.html