Jump to content

Validating Against Values in a Database


Guest akigo1989

Recommended Posts

Guest akigo1989

I need my application to check whether some values exist in the database to prevent duplicates.In old ASP I used the recordset and checked if the value(s) in the form already exist, but can't figure out how to do it using ASP.NET (C# as the language), any help appreciated.

Link to comment
Share on other sites

For SQLServer, I usually do it something like this. Other databases may use a slightly different Connection class (i.e. System.Data.OdbcConnection).First, make sure your class references the following:

public bool Exists(int id){    bool exists = false;    using(SqlConnection connection = new SqlConnection("CONNECTION STRING GOES HERE"))    {        // I usually use Stored Procedures, but this will work too...        SqlCommand command = new SqlCommand("SELECT MyID FROM MyTable WHERE MyID = " + id, connection);        command.CommandType = CommandType.Text;        try        {            connection.Open();            object result = command.ExecuteScalar();            if(id == (int)result)            {                exists = true;            }        }        catch(Exception e)        {            // do whatever exception handling you require.        }        command.Dispose();    }        return exists;}

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...