2013-06-22 88 views
0
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()); 
} 

我已创建一个登录表单,并在Microsoft Access一个表中包含用户名和密码fields.when我点击登录按钮,它总是显示其他消息,虽然用户名和密码是相同表。访问数据库的登录表单

+1

你有什么问题吗? – Raptor

+0

也许实际上在你的查询字符串中传递密码? 'txtlognpswrd'应该是'txtlognpswrd.Text'。 **但是** - 请学习并使用参数化查询来防止SQL注入攻击。 – Tim

回答

3

单词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"); 
} 
+0

谢谢你...这是我的错误,我忘了写txtLognpswrd后的文本..和耶参数化查询也是伟大的概念...再次感谢 –