登录形式访问数据库 [英] Login form with access database

查看:188
本文介绍了登录形式访问数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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我点击登录按钮,它总是显示其他消息虽然用户名和密码是相同的表。

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.

推荐答案

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

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

这篇关于登录形式访问数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆