English 中文(简体)
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?
最佳回答

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
问题回答

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 

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.





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签