0

Hi I am new to using Microsoft Access as a database for Visual Studio (previously I used SQL Server) so I am unsure how to go about the usual tasks such as accessing the database. At the minute I am trying to write code to check if a username already exists in the database, if it does I want it to inform the user, if not it should go ahead and insert the record. So far after researching this is the code I have came up with

 String regUser = txtNewUser.Text;

            OleDbConnection conn;
            OleDbCommand cmd;

            using (conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ProjectDatabaseConnectionString"].ConnectionString))
            {
                using (cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "SELECT * FROM Users WHERE username=?";
                    cmd.Parameters.AddWithValue("username", txtNewUser.Text);

                    object username = cmd.ExecuteScalar();
                    if (username == null)
                    {

                    }
                }

however I am unsure if this is correct. Can anyone help or even direct me to a tutorial on using Access as the database.

Thanks in advance

2
Contributors
1
Reply
12
Views
3 Years
Discussion Span
Last Post by __avd
0

You need to correct the parameter name and SELECT statement. You can either use ? or @paramName.

cmd.CommandText = "SELECT username FROM Users WHERE username=@username";
cmd.Parameters.AddWithValue("@username", txtNewUser.Text);

PS: ExecuteScalar() returns value from 1st column and 1st row.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.