C# 带有访问数据库的登录表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17249797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Login form with access database
提问by Jay Desai
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());
}
I have created one login form and one table in microsoft access which contains username and password fields.when i click on login button it always shows else message though the username and password is same as in table.
我在 microsoft access 中创建了一个登录表单和一张表,其中包含用户名和密码字段。当我点击登录按钮时,它总是显示其他消息,尽管用户名和密码与表中的相同。
采纳答案by Steve
The word PASSWORD is a reserved keyword in access-jet. You need to encapsulate it in square brackets.
单词 PASSWORD 是 access-jet 中的保留关键字。您需要将其封装在方括号中。
OleDbCommand cmd = new OleDbCommand("select * from Login where Username=" +
"? and [Password]=?", con);
Also do not use string concatenation to build sql commands but a parameterized query
也不要使用字符串连接来构建 sql 命令,而是使用参数化查询
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
上面的代码中还有其他问题。
首先尝试使用 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");
}

