login.aspx页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="webRoot_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"> <script src="../js/jquery-1.4.1-vsdoc.js" type="text/javascript"></script> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="用户名:"></asp:Label> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br /> <asp:Label ID="Label2" runat="server" Text="密 码:"></asp:Label> <asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox><br /> <asp:Button ID="Button1" runat="server" Text="登录" /> </div> </form> </body> </html>
login.aspx.cs页面:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Configuration; public partial class webRoot_login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { query(); } public void query() { string str = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString; //连接数据库,在webconfig中配置 SqlConnection Conn = new SqlConnection(str); Conn.Open(); string sql = "select * from userInfo where userName=@UserName and password=@PassWord" ; SqlCommand Comm = new SqlCommand(sql, Conn); Comm.Parameters.Add("UserName",TextBox1.Text); Comm.Parameters.Add("PassWord",TextBox2.Text); SqlDataReader sdr = Comm.ExecuteReader(); if (sdr.Read()) { Session["UserName"] = TextBox1.Text; Session["PassWord"] = TextBox2.Text; Label1.Text = "登陆成功!"; } else { Label1.Text = "无法登陆,用户名或密码错误!"; } Conn.Close(); } }
web.config页面:
<?xml version="1.0"?> <!-- 有关如何配置 ASP.NET 应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <connectionStrings> <add name="ConnStr" connectionString="Data Source=5KVR6JEFONLYFSU;Initial Catalog=test;uid=sa;pwd=123;Integrated Security=True"/> </connectionStrings> <system.web> <compilation debug="true" targetFramework="4.0"/> </system.web> </configuration>
今天学会把数据库连接方式连接方式写在web.config中。5KVR6JEFONLYFSU是服务器名;test是数据库名;sa是用户名;123是密码;userInfo是其中的一个表,字段名如下图:
后面会慢慢的增加难度,如用户名密码都不能为空,写在javascript中