带访问数据库的登录表单

try { OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= C:\Users\jay.desai\Documents\Visual Studio 2008\Projects\Jahoo Sign in form!\Jahoo Sign in form!\Registration_form.mdb"); con.Open(); OleDbCommand cmd = new OleDbCommand("select * from Login where Username='"+txtlognUsrnm.Text+"' and Password='"+txtlognpswrd+"'", con); OleDbDataReader dr = cmd.ExecuteReader(); if(dr.Read() == true) { MessageBox.Show("Login Successful"); } else { MessageBox.Show("Invalid Credentials, Please Re-Enter"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } 

我在微软访问中创建了一个登录表单和一个表,其中包含用户名和密码字段。当我点击登录按钮时,它总是显示其他消息,尽管用户名和密码与表中相同。

PASSWORD这个词是access-jet中的保留关键字。 您需要将其封装在方括号中。

 OleDbCommand cmd = new OleDbCommand("select * from Login where Username=" + "? and [Password]=?", con); 

也不要使用字符串连接来构建sql命令,而是使用参数化查询

您的代码中还有其他问题。
首先尝试使用using语句以确保连接和其他一次性对象正确关闭和处置。
其次,如果您只需要检查登录凭据,则无需返回整个记录,您可以使用ExecuteScalar方法来避免OleDbDataReader对象

 string constring = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= C:\Users\jay.desai\Documents\Visual Studio 2008\Projects\Jahoo Sign in form!\Jahoo Sign in form!\Registration_form.mdb"; string cmdText = "select Count(*) from Login where Username=? and [Password]=?" using(OleDbConnection con = new OleDbConnection(constring)) using(OleDbCommand cmd = new OleDbCommand(cmdText, con)) { con.Open(); cmd.Parameters.AddWithValue("@p1", txtlognUsrnm.Text); cmd.Parameters.AddWithValue("@p2", txtlognpswrd.Text); // <- is this a variable or a textbox? int result = (int)cmd.ExecuteScalar() if(result > 0) MessageBox.Show("Login Successful"); else MessageBox.Show("Invalid Credentials, Please Re-Enter"); }