I need help for connecting my 'Access' database to asp.net website. Coding is in C# .
I was working on making a registration page, but since i was unable to connect, I tried a test code for login and it ain't working :icon_cry:

I am using the following code for showing form :

<asp:Literal ID="Literal1" runat="server" /><br />
    User Name: <asp:TextBox ID="uname" runat="server" /><br />
    Password:  <asp:TextBox ID="upassword" runat="server" TextMode="Password" /><br />
    <asp:Button ID="Login" runat="server"  Text="Log In" onclick="Login_Click" />

I am using following code in .cs file :

string connect = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=C:|Users|Apache|Documents|jerry.mdb; User Id=Admin; Password=";
        string query = "Select Count(*) From registration Where uname = ? And upassword = ?";
        int result = 0;
        using (OleDbConnection conn = new OleDbConnection(connect))
        {
            using (OleDbCommand cmd = new OleDbCommand(query, conn))
            {
                cmd.Parameters.AddWithValue("", uname.Text);
                cmd.Parameters.AddWithValue("", upassword.Text);
                conn.Open();
                Session["registration"] = uname.Text;
                result = (int)cmd.ExecuteScalar();
            }
        }
        if (result > 0)
        {
            Response.Redirect("LoggedIn.aspx");
        }
        else
        {
            Literal1.Text = "Invalid credentials";
        }

I have also included 'using System.Data.OleDb;' in starting.. and on running this test page, I get the following errors :

Source Error:

Line 30:                 cmd.Parameters.AddWithValue("", uname.Text);
Line 31:                 cmd.Parameters.AddWithValue("", upassword.Text);
Line 32:                 conn.Open();
Line 33:                 Session["registration"] = uname.Text;
Line 34:                 result = (int)cmd.ExecuteScalar();


Source File: c:\Users\Apache\Documents\Visual Studio 2008\WebSites\onlineshoppingplace\test.aspx.cs    Line: 32

I even included the database 'jerry.mdb' to my database connection, started it from Control Panel > ODBC too.. I would be thankful if someone can teach me about it from 0 level (I mean that maybe I am doing something wrong with database :icon_mad: :confused:)

Dani AI

Generated

Likely causes are already visible in the thread: an invalid connection string/path, a provider mismatch, empty parameter names and/or file-permission issues. correctly flagged the path separator problem; correctly flagged the empty parameter names; pointed toward keeping the connection string in config. The runtime error at the line shown (around conn.Open()) usually means the provider cannot find or open the .mdb file (bad path, wrong provider, or no access), not the ExecuteScalar call itself.

Quick checklist to isolate the problem

  • Put the .mdb inside the web app (App_Data) and use a reliable path resolver (Server.MapPath or |DataDirectory|) rather than a hard-coded user folder.
  • Use the correct OLE DB provider: Jet is 32-bit only; on 64-bit hosts either enable 32-bit in the app pool or use the ACE provider.
  • Grant the application identity read/write (or at least read) permissions on the folder that holds the .mdb.
  • Don’t pass empty parameter names. With OleDb the parameter order matters; add real parameters (or OleDbParameter objects) and match the order of the placeholders.
  • Wrap open/execute calls in try/catch and log the full exception + InnerException to get the real failure text.

A safe pattern (C#) — read the connection string from config, fetch the stored password hash by username, then verify in code:

var cs = System.Configuration.ConfigurationManager.ConnectionStrings["MyAccess"].ConnectionString;
using (var cn = new System.Data.OleDb.OleDbConnection(cs))
using (var cmd = cn.CreateCommand())
{
    cmd.CommandText = "SELECT PasswordHash FROM registration WHERE uname = ?";
    cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("uname", System.Data.OleDb.OleDbType.VarChar) { Value = uname.Text.Trim() });
    cn.Open();
    var stored = cmd.ExecuteScalar() as string;
    if (stored != null && VerifyHash(upassword.Text, stored))
    {
        Session["registration"] = uname.Text;
        Response.Redirect("LoggedIn.aspx");
    }
    else
    {
        Literal1.Text = "Invalid credentials";
    }
}

Notes: replace VerifyHash with a proper password hashing check; avoid storing plain text passwords. For production or concurrent users prefer SQL Server Express / LocalDB rather than an Access file. If the problem persists after the checklist, capture the exact exception message and inner exception for the next diagnostic step.

Recommended Answers

All 7 Replies


---------
using System.Data;
using System.Data.SqlClient;
public class Class1

{
SqlConnection cnn;
SqlCommand cmd;
SqlDataAdapter da;
DataSet ds;
DataTable dt;

public Class1()
{
//
// TODO: Add constructor logic here
//
}
public DataTable getdata(string query)
{
cnn = new SqlConnection();

cnn.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True";

cmd = new SqlCommand();

cmd.Connection = cnn;

cmd.CommandText = query;

da = new SqlDataAdapter();

da.SelectCommand = cmd;

ds = new DataSet();

da.Fill(ds);

dt = new DataTable();

dt = ds.Tables[0];

return dt;

}

-------------

---------------
Class1 a = new Class1();
protected void Page_Load(object sender, EventArgs e)
{

GridView1.DataSource = a.getdata("select * from student");
GridView1.DataBind();
}

Thank you very much for taking time to reply to my query :D,

But my dear friend, I need to understand for "MS ACCESS", I am using the above code and getting errors... I need help with "log in" form with ACCESS :D

Sighh.. Further help will be appreciated
Thanks in advance

I could be wrong, but shouldn't the connection path have "\\" between the folders instead of "|"?

Yes, Your connection string seems wrong. You need to use "\\" instead of pipe sign "|". Also I believe below portion is also wrong.

cmd.Parameters.AddWithValue("", uname.Text);
cmd.Parameters.AddWithValue("", upassword.Text);

In above both lines you need to give either "?" or any valuable name like "@uname" and so on. You can't leave it blank.

Try by this and let us know.

Err.. I tried the above suggestion by you :
to use '@uname' and with '?'

But still I am having problem connecting with the database, btw, it will be great if someone can write the code for access here and i can test that one against mine.. ?

I am not having problems with SQL connection though :((

I give you my code, but it's in vb, but I'm sure you can translate it

Public Shared Function check_UserCredentials(ByVal username As String, ByVal pass As String) As Boolean

Dim userID As Long
Dim sqlstring As String
sqlstring = "SELECT UserID from tblUsers WHERE Username=? AND Pass=? "
Try
Using cn As New OleDbConnection(WebConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString)

Using dbcomm As New OleDbCommand(sqlstring, cn)
dbcomm.Parameters.AddWithValue("Userername", username)
dbcomm.Parameters.AddWithValue("Pass", pass)
cn.Open()
userID = dbcomm.ExecuteScalar
cn.Close()
End Using

End Using
If userID <> Nothing And userID > 0 Then
Return True
Else
Return False
End If

Catch ex As Exception

Return False
End Try

End Function

And in your web.config file have


<connectionStrings>
<add name="MyConnectionString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Mydb.mdb" providerName="System.Data.OleDb"/>
</connectionStrings>

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.