asp.net连接Access数据库实现登陆功能

这里话就不多说了,直接演示代码。

连接access数据库首先需要配置web.config

 <appSettings>
    <add key="AccessConnString" value="provider=microsoft.jet.oledb.4.0;data source="/>
    <add key="AccessDbPath" value="~/App_Data/News.mdb"/>
  </appSettings>
  <connectionStrings>
    <add name="AccessConnectionString" connectionString="Provider=Microsoft.Jet.Oledb.4.0;data source="/>
    <add name="Access_Path" connectionString="~/App_Data/News.mdb"/>
    <add name="SqlConnectionString" connectionString="Data Source=localhost;Initial Catalog=HuaRunDb;User ID=sa;password=zhuwenfan;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

首先要在你得根目录新建一个App_Data文件夹,将数据库文件移至该文件夹中,然后就可以把以上代码写入配置文件中了。

前台:

 <table>
        <tr><td>用户名:</td><td>
            <asp:TextBox ID="Textuser" runat="server"></asp:TextBox></td></tr>
        <tr><td class="auto-style1">&nbsp;密码:</td><td class="auto-style1">
            <asp:TextBox ID="Textpw" runat="server"></asp:TextBox></td></tr>
        <tr>
            <td></td><td><asp:Button ID="Button1" runat="server" Text="登陆" Width="92px" OnClick="Button1_Click" /></td></tr>
    </table>

后台:

public partial class Login : System.Web.UI.Page
    {
        public static readonly string connStr1 = "Provider = Microsoft.Jet.OLEDB.4.0 ;Data Source=" + HttpContext.Current.Server.MapPath("~/App_Data/News.mdb");//连接数据库
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            OleDbConnection connection = new OleDbConnection(connStr1);
            connection.Open();//打开数据库
            string sql = "select * from [User] where UserName = '" + Textuser.Text + "' and Userpw = '" + Textpw.Text + "'";//查询用户名和密码匹配的哪一条数据
            OleDbCommand command = new OleDbCommand(sql, connection);
            OleDbDataReader reader = command.ExecuteReader();
            if (reader.Read())//如果匹配成功读取数据库内容
            {
                Session["username"] = Textuser.Text;//将用户名保存到session中
                Response.Redirect("News.aspx");
                connection.Close();//关闭数据库
                Response.End();
            }
            else  
            {
                Response.Write("<script>alert('用户名或密码错误!!')</script>");//否则登陆失败
            }

        }
    }

这只是最简单的登陆,仅供参考,如果有什么不足的地方可以提出来。

原文地址:https://www.cnblogs.com/lihuazou/p/4156766.html