简体   繁体   中英

How can I know if such value exists in database? (ADO.NET)

For example, I have a table, and there is a column named 'Tags'. I want to know if value 'programming' exists in this column. How can I do this in ADO.NET?

I did this:

OleDbCommand cmd = new OleDbCommand("SELECT * FROM table1 WHERE Tags='programming'", conn);
OleDbDataReader = cmd.ExecuteReader();
What should I do next?

use SELECT COUNT(*) and check the results. (and use ExecuteScalar)

(assuming you know how to set the connection and use it)

SELECT  TOP 1 1
FROM    table1
WHERE   Tags='programming'

better version, it is a good practice to use parameters instead of string concatenation, see sql injection

OleDbCommand cmd = new OleDbCommand("SELECT TOP 1 1
 FROM table1 WHERE Tags=?", conn);
cmd.Parameters.Add("@p1", OleDbType.VarChar).Value = "Programming";
OleDbDataReader rdr = cmd.ExecuteReader();
if(rdr.Read())
    // record exists
else
   //Not exists

You should do two things:

If you are just checking the presence of a tag called Programming, you should change your query to return a COUNT instead of returning all rows.

SELECT TOP 1 Column1 FROM Table1 WHERE Tags = 'Programming'

You should check the returned set in the reader to see if there are any rows. If there are, then it means that the tag exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM