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

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.

Related

How to use value from SQL Server in C#

I got value from SQL Server using this C# code:
SqlDataReader reader = new SqlCommand("select Top 1 Client From _ClientName group by Client order by count(*) desc", sqlCon.ShardDB).ExecuteReader();
How can I use this value again to insert it into another table?
Just use name of the column begin returned from the database i.e "Client" here. If it is a string, you can use .ToString(). If it is another type, you need to convert it using System.Convert
string Value = reader["Client"].ToString();
First, for readability sake, try separating your code into separate lines, like so:
SQLReader reader;
SQLCommand SQLCmd = new SQLCommand();
SQLCmd.CommandText = "select Top 1 Client From _ClientName group by Client order by count(*) desc";
SQLCmd.Connection = sqlCon.SharedDB;
reader.Execute(SQLCmd);
If I understood your comment to Sajeetharan's previous answer, you want to know how to advance to the next result if your query returns more than one. Have you tried SQLReader.Read()?
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx

Syntax error while trying to fetch data from MySql

So I am trying to fetch a value from the database, selecting the row using WHERE INT.
conn = new MySqlConnection(DBdetails.connStr);
conn.Open();
query = "SELECT * FROM tables WHERE table=#tafel";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("#tafel", tafel);
cmd.ExecuteNonQuery();
However it wont pass 'cmd.ExecuteNonQuery()', it throws a error saying the syntax isnt right like: "near table=1", "near table=2"
I tried fetching a other one in the same table that is a var char and it worked perfectly.
Don't really see what I am doing wrong. The 'table' column is a int and 'tafel' is a int to.
Thanks!
Put your field name table in backticks (table is a reserved word in MySQL) :
query = "SELECT * FROM `tables` WHERE `table` = #tafel";
As others said, table is a reserved word in MySQL. You need to use quote with it like
query = "SELECT * FROM tables WHERE `table` = #tafel";
However, the best solution is to change the name to a nonreserved word.
Also use using statement to dispose your MySqlConnection and MySqlCommand like;
using(MySqlConnection conn = new MySqlConnection(DBdetails.connStr))
using(MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM tables WHERE `table` = #tafel";
cmd.Parameters.AddWithValue("#tafel", tafel);
conn.Open();
cmd.ExecuteNonQuery();
}
By the way, I don't understand why you use ExecuteNonQuery with SELECT statement. It just executes your query. It doesn't even return any value.
If you want to get the result of your query, you can use ExecuteReader method which returns SqlDataReader as your result rows.

Query is always returning -1 in C#

I am using following code to check if record exist.
SqlCommand check_Campaign_Name = new SqlCommand("SELECT * FROM Campaign_Summary WHERE ([Compaign_Name] = #user) ", conn);
check_Campaign_Name.Parameters.AddWithValue("#user", txtBox_LastClick_Campaign.Text);
int CampaignExist = check_Campaign_Name.ExecuteNonQuery();
richTextBox1.Text = CampaignExist.ToString();
But I am always getting -1 in the integer CampaignExist. Don't know where I am doing wrong.
ExecuteNonQuery is not supposed to return the number of rows SELECTED, but the number of rows modified by an INSERT/UPDATE/DELETE command. You should use a SqlDataReader and check with its property HasRows or use an aggregate function like COUNT and ExecuteScalar
(Probably the best choiche if you want to just retrieve the number of rows)
SqlCommand check_Campaign_Name = new SqlCommand("SELECT COUNT(*) FROM Campaign_Summary " +
"WHERE Compaign_Name = #user", conn);
check_Campaign_Name.Parameters.AddWithValue("#user", txtBox_LastClick_Campaign.Text);
int rowCount = Convert.ToInt32(check_Campaign_Name.ExecuteScalar());
However, if you want only to know if the row exists or not, then the COUNT approach is considered less efficient than using the EXISTS statement.
string cmdText = #"IF EXISTS (SELECT Compaign_Name FROM Campaign_Summary
WHERE Compaign_Name = #user)
SELECT 1 ELSE SELECT O";
SqlCommand check_Campaign_Name = new SqlCommand(cmdText, conn);
int rowExists = Convert.ToInt32(check_Campaign_Name.ExecuteScalar());
This second approach just allows to know if there are rows that fits the WHERE statement or not.
So it is not exactly like COUNT(*) where you get the exact number of rows.
Use executescalar method and count on query
SqlCommand check_Campaign_Name = new SqlCommand("SELECT COUNT(1) FROM Campaign_Summary WHERE ([Compaign_Name] = #user) ", conn);
check_Campaign_Name.Parameters.AddWithValue("#user", txtBox_LastClick_Campaign.Text);
int CampaignExist = Convert.ToInt32(check_Campaign_Name.ExecuteScalar());
richTextBox1.Text = CampaignExist.ToString();
From MSDN,
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.
As your query is a SELECT and not one of the mentioned UPDATE, INSERT or DELETEs, it will always return -1.
Try with Execute scalar MSDN
int CampaignExist = Convert.ToInt(check_Campaign_Name.ExecuteScalar());
SqlCommand check_Campaign_Name = new SqlCommand("SELECT COUNT(1) FROM Campaign_Summary WHERE ([Compaign_Name] = #user) ", conn);
check_Campaign_Name.Parameters.AddWithValue("#user", txtBox_LastClick_Campaign.Text);
int CampaignExist = Convert.ToInt32(check_Campaign_Name.ExecuteScalar());
richTextBox1.Text = CampaignExist.ToString();
ExecuteNonQuery is not used to retrieve results
You can use one of the following methods:
SqlCommand.ExecuteScalar (I would prefer this)
DataAdapter.Fill

C# SQL if query returns any rows count

What is the simplest and most efficient way to find if a data returns using a query? I'm using DataTable like sqlAdapter.Fill(_table1) and then doing _table1.Rows.Count to see if a datatable has any rows. Is there any classes and functions in C# that just gives me if there are any rows. I don't need the data of the rows. Just the count is what I need. I'm running this query against very large datasets so I don't wanna fill the datatable with all the row info.
string myScalarQuery = "select count(*) from TableName";
SqlCommand myCommand = new SqlCommand(myScalarQuery, myConnection);
myCommand.Connection.Open();
int count = (int) myCommand.ExecuteScalar();
myConnection.Close();
Possible optimization of the query per the comments bellow:
Select Top 1 * FROM TableName
The least expensive way is using SqlDataReader's HasRows property
UPDATE: of course, the most efficient SELECT query will be like "Select Top 1 1 FROM TableName", which doesn't even need to pull any column data.
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
...
}
}

Need sql for creating view set in asp.net c#

I am using sqlconnection. I want to create a view and select from the view set.
Like I have shown below I have created a view called vwtopic.. from this I need to select distinct values of a column.
I cannot put in one easy statment because i need distinct values of topic column only and need to order by another column datetime..
So I am first creating a view where I am ordering by datetime and from this I am selecting distinct topic.
Problem is I am able to create a view set, but from this I am not able to select the distinct topic data to a SqlDataAdapter.. I frankly dont know the syntax.. I have not tried this before..
First part:
SqlConnection con = new SqlConnection("server=xxxx;database=wbsd;user id=***;password=***;");
SqlCommand add = new SqlCommand("CREATE VIEW vwtopic AS SELECT * FROM sr_topic_comment ORDER BY datetime DESC", con);
try
{
add.Connection.Open();
add.ExecuteNonQuery();
add.Connection.Close();
}
catch (System.FormatException)
{
}
Second part:
String sqlcmd = "SELECT DISTINCT topic FROM vwtopic WHERE owner='" + owner + "'";
SqlDataAdapter adap = new SqlDataAdapter(sqlcmd,con);
Instead of creating Views in Code, use the "WITH" statement or Sub-queries this should meets your needs:
WITH [vwtopic] AS (
SELECT * -- I recommend using each column name
FROM [sr_topic_comment]
-- not sure if ORDER BY is allowed here:
-- ORDER BY [datetime] DESC
)
SELECT DISTINCT [topic] FROM [vwtopic] -- add WHERE, ORDER BY
Since the view you are creating does not have any filters defined, selecting distinct values from the view is equivalent to selecting distinct values from the table. When selecting distinct values, you can only order by those values (not the datetime column as you're attempting here). Therefore, you can do:
SqlCommand cmd = new SqlCommand("SELECT DISTINCT topic FROM sr_topic_comment WHERE owner = #owner", con);
cmd.Parameters.Add(new SqlParameter(#owner, SqlDbType.Varchar, 25));
cmd.Parameters["#owner"].Value = owner;
DataSet ds = new DataSet();
using (SqlDataAdapter adap = new SqlDataAdapter(cmd)) {
adap.Fill(ds);
}
This will give you a DataSet filled with the distinct values from the table that meet the filter criteria (owner == the supplied owner).
I found the answer below will do the trick for me...
I am filling the result in dataset and calling my required column 'topic'..
SELECT DISTINCT topic,datetime FROM sr_topic_comment WHERE owner='sr' ORDER BY datetime DESC
Thank you very much for your inputs.. I learnt about WITH clause today.. cheers..

Categories