user2818136
user2818136

Reputation:

How do I check if the value is already present in the database?

Is there a easier way to check the value entered in the textbox with the field in the database if it is already present or not? Because I find this a little complex. Thanks in advance.

    public int method(string a)
    {
        string str;
        int chk = 1;
        con = new OracleConnection(constr);
        con.Open();
        try
        {
            com = new OracleCommand("select a from table where a='" + a + "'", con);
            OracleDataReader dr;
            dr = com.ExecuteReader();

            if (dr.Read())
            {
                str = dr["A"].ToString();
                if (str == a)
                    chk = 0;
                else
                    chk = 1;
            }
            else
                chk = 1;
            return chk;
        }
        catch (Exception e)
        {
            throw new Exception(e.Message);
        }

    }

Upvotes: 1

Views: 982

Answers (2)

Adil
Adil

Reputation: 148110

You can use Read to decide if you got exact match as the query you have already check if the given value is present in database table. OracleDataReader.Read will return true if you get atleast one row.

if (dr.Read())
   return 1;             
else     
    return 0;

Read returns true if there are more rows; otherwise, false, Reference.

You can change the return type of method to bool and simply return result of read;

return dr.Read()

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062630

Firstly, don't concatenate. Use parameters. Since you are using oracle that is :name syntax, IIRC. Secondly, you can use ExecuteScalar to be simpler, i.e.

public bool RecordExists(string a)
{
    using(var con = new OracleConnection(constr))
    using(var cmd = con.CreateCommand())
    {
        cmd.CommandText = "select 1 from table where a=:a";
        cmd.Parameters.AddWithValue("a", a);
        con.Open();
        return cmd.ExecuteScalar() != null; // returns null if no rows
    }
}

But frankly, you can also use tools like "dapper" to make it easier:

public bool RecordExists(string a)
{
    using(var con = new OracleConnection(constr))
    {
        return con.Query("select 1 from table where a=:a", new {a}).Any();
    }
}

(and yes, I know I didn't even Open() the connection)

Upvotes: 1

Related Questions