且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

登录形式访问数据库

更新时间:2022-11-25 08:46:37

这个词密码在访问喷射保留关键字。您需要将其封装在方括号。

The word PASSWORD is a reserved keyword in access-jet. You need to encapsulate it in square brackets.

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



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

Also do not use string concatenation to build sql commands but a parameterized query

有以上代码中的其他问题。结果
首先尝试使用using语句,以确保连接等一次性物品的正确关闭和处置。结果
第二,如果你只需要检查登录凭据,那么就没有必要取回全程记录,你可以使用ExecuteScalar方法避免了OleDbDataReader对象

There are other problems in your code above.
First try to use the using statement to be sure that the connection and other disposable objects are correctly closed and disposed.
Second, if you need only to check the login credentials, then there is no need to get back the Whole record and you could use the ExecuteScalar method avoiding the OleDbDataReader object

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");
}