How to check whether the record exists or not in the database while inserting new record using C#?
This code is used when unique logins have to be created as same credentials can not be provided to user. Depending up on the boolean value returned by the function, you can display success or failure message to user.
I hope it will be useful for you all.
Example:
Suppose user wants to add new unique record to the database then he needs to check whether that record is already present in database or not. If it is present then function will return true else false.
public bool checkRecordExistsOrNot(string login)
{
string ConnString = GetConnString();
string sqlString = "SELECT yourtablename.yourcolumnname FROM yourtablename WHERE yourcolumnname= ?";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(sqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("?yourcolumnname", OleDbType.VarChar).Value = login;
conn.Open();
if (cmd.ExecuteScalar() != null)
{
conn.Close();
conn.Dispose();
return true;
}
else
{
conn.Close();
conn.Dispose();
return false;
}
}
}
}
GetConnString() method is used to return the value of ConnectionString which is stored in web.config.
public static string GetConnString()
{
return ConfigurationManager.AppSettings["ConnectionString"].ToString();
}