Check duplicate username with parameterized query - c#

I want to check if username already exist in the database.
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["DBCOnn"].ToString());
try
{
con.Open();
SqlCommand cmd = new SqlCommand("select client_id from tbl_client where client_name=#cname", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#cname", DbType.String).Value = usernm;
int i = cmd.ExecuteNonQuery();
if (i > 0)
return true;
else
return false;
}
catch (Exception ex)
{
throw new Exception("CheckExistingClient:" + ex.Message, ex.InnerException);
}
finally
{
con.Close();
}
But here, i always giving as -1
What is the problem.?

ExecuteNonQuery returns the number of affected rows and is used normally for insert-, update- or delete-statements. Use ExecuteScalar with COUNT instead.
using (var con = new SqlConnection(ConfigurationManager.AppSettings["DBCOnn"].ToString()))
using(var cmd = new SqlCommand("select COUNT(client_id) from tbl_client where client_name=#cname", con))
{
cmd.Parameters.Add("#cname", DbType.String).Value = usernm;
con.Open();
int i = (int)cmd.ExecuteScalar();
return i > 0;
}
Here is a related answer on SO: https://stackoverflow.com/a/4269651/284240

ExecuteNonQuery returns the number of rows affected by an INSERT, UPDATE or DELETE statement. You're running a SELECT.
I find it's easier to "SELECT FROM Users where UserName=#cName" and run a standard Select.

ExecuteNonQuery is meant for DML queries. You are not modifying and rows. So you get the result as -1.
You could use select count(client_id) from tbl_client where client_name=#cname
And get the count with cmd.ExecuteScalar

Related

Select those emails from db if they wanted to get an email

I am developing a system that heavily relies on emailing, I'm trying to determine if users wanted to get notified or not.
User details are stored in SQL Server Express. I want to check which registered users wanted to receive and get their emails from the database. Is this possible?
So far I got this far:
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "SELECT COUNT(*) FROM [UserTable] WHERE ([price] = #price)";
command.Parameters.AddWithValue("#price", "10.000");
try
{
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
}
catch (SqlException ex)
{
MessageBox.Show("Error is SQL DB: " + ex);
}
finally
{
connection.Close();
}
}
It returns -1, but I have a 10.000 in one row. And from here I want to save the email addresses of those who has 10.000 on their preferences from the db so I can add it to email list.
So to summarize: Check all rows if some of them has 'yes' and save their 'email' from the same row.
Can someone point me to the right direction? Thank you.
Updated it for #SeM
private void getMailList()
{
using (SqlConnection connection = new SqlConnection("Data Source=DESKTOP-9MMTAI1\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
{
try
{
connection.Open();
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "SELECT COUNT(*) FROM UserTable WHERE price = #price";
cmd.Parameters.Add(new SqlParameter("#price", 10000));
int count = int.Parse(cmd.ExecuteScalar());
}
}
catch (Exception ex)
{
MessageBox.Show("Error is SQL DB: " + ex);
//Handle your exception;
}
}
}
ExecuteNonQuery returning the number of rows that affected only for Update, Insert and Delete statements. In your case, you will always get get -1, because on Select statement ExecuteNonQuery returning -1
So try this:
using(SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
using(SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "SELECT COUNT(*) FROM UserTable WHERE price = #price";
cmd.Parameters.Add(new SqlParameter("#price", 10000));
int count = int.Parse(cmd.ExecuteScalar());
}
}
catch (Exception ex)
{
//Handle your exception;
}
}
As commented above, ExecuteNonQuery does just that - no query results.
Instead:
int recordsAffected = (int)command.ExecuteScalar();

How can I get combobox ID to return to database

void fill_cbcategoria()
{
try
{
con.Open();
string Query = "select * from Categoria";
SqlCommand createCommand = new SqlCommand(Query, con);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
string categoria = (string)dr.GetString(1);
cbcategoria.Items.Add(categoria);
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am using this code to fill my category combobox:
private void btneditar_Click(object sender, EventArgs e)
{
try
{
con.Open();
string Query = "insert into dbPAP.Categoria (id_categoria, categoria)" + "values('" + this.cbcategoria.SelectedValue + this.cbcategoria.SelectedItem + "') ;";
SqlCommand createCommand = new SqlCommand(Query, con);
SqlDataReader dr = createCommand.ExecuteReader();
MessageBox.Show("Editado com sucesso!");
while (dr.Read())
{
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Now I want to update data to database, but is needed "id_categoria" but I don''t know how can I do it. In Table "Categoria" just got 2 parameters, that's "id_categoria" = 0 and "categoria" = 1. Problem is, can I get "id_categoria" value to update in database using combobox.SelectedItem?
Use executeNonQuery for executing insert command. SqlDataReader is usually used for read data from the database; you can try like the following:
string Query = "insert into dbPAP.Categoria (id_categoria,categoria)values(#selectedVal,#selectedItem)";
SqlCommand createCommand = new SqlCommand(Query, con);
createCommand.Parameters.Add("#selectedVal", SqlDbType.VarChar).Value = this.cbcategoria.SelectedValue;
createCommand.Parameters.Add("#selectedItem", SqlDbType.VarChar).Value = this.cbcategoria.SelectedItem;
createCommand.ExecuteNonQuery();// return 1 in this case if insert success
few suggestions for better understanding:
ExecuteReader : ExecuteReader used for getting the query results as a DataReader object. It is readonly forward only retrieval of records and it uses select command to read through the table from the first to the last.
ExecuteNonQuery : ExecuteNonQuery used for executing queries that does not return any data. It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected.
You can read more about The purpose of parameterized queries

How to save the result of a SQL query in a variable in c#?

I want to try to save the result of this query (I want to get the value of the primary key) into a variable in c# of a MDB database but I don't know how I can do it:
SELECT ##identity FROM Table
I've tried this but it doesn't work:
int variable;
variable = cmd.CommandText("SELECT ##IDENTITY FROM TABLE");
PD: It isn't all the code, I have a problem only with this part.
You can use this snippet:
SqlCommand command = new SqlCommand(
"SELECT ##IDENTITY FROM TABLE",
connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
Is it complete code? You just created command object, but didn't open the connection and did not run the command.
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("SELECT ##IDENTITY FROM TABLE", conn);
try
{
conn.Open();
newID = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

How to return the ID of the Inserted Record to C#

I have this stored procedure:
Insert into dbo.file_row (file_sub_type) values (#file_sub_type)
DECLARE #result int;
SET #result = SCOPE_IDENTITY()
RETURN #result;
This works fine to return the id in SSMS. However, when I call it from C#, it returns -1.
var connection = GetSqlConnection();
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "InsertInto_file_row";
command.Parameters.Add(new SqlParameter("#file_sub_type", fileType));
int result = command.ExecuteNonQuery();
connection.Close();
return result;
I don't see what I am doing wrong. I just need the Id of the inserted record.
Greg
Check the docs on ExecuteNonQuery():
Executes a Transact-SQL statement against the connection and returns the number of rows affected.
(Emphasis mine)
If you want to get information back, you have a couple options:
Change RETURN to SELECT and ExecuteNonQuery() to ExecuteScalar()
Use an OUTPUT parameter
To add on to Joel's response
Try ExecuteScalar instead
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. (Overrides DbCommand.ExecuteScalar().)
This will help you. The function returns the new Identity column value if a new row was inserted, 0 on failure. It is from MSDN
static public int AddProductCategory(string newName, string connString)
{
Int32 newProdID = 0;
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = newName;
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int)newProdID;
}
public int AddProductCategory(string newName, string connString)
{
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#Name", newName);
con.Open();
latestInsertedId = (int)cmd.ExecuteScalar();
con.Close();
}
return latestInsertedId ;
}
}

Retrieve number of columns in SQL Table - C#

I'm very new to C#. I'm trying to retrieve the number of columns using:
SELECT count(*) FROM sys.columns
Could you please explain how to use the command and put it into a variable.
To connect to the database you can use the SqlConnection class and then to retrieve the Row Count you can use the Execute Scalar function. An example from MSDN:
cmd.CommandText = "SELECT count(*) FROM sys.columns;";
Int32 count = (Int32) cmd.ExecuteScalar();
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection
You will need to use ExecuteScalar as the others have said. Also, you will need to filter your SELECT on the object_id column to get the columns in a particular table.
SELECT count(*) FROM sys.columns WHERE object_id = OBJECT_ID(N'table_name')
Alternatively, you could do worse than familiarise yourself with the ANSI-standard INFORMATION_SCHEMA views to find the same information in a future-proof, cross-RDBMS way.
You have to use a command and retrieve back the scalar variable :
SqlCommand cmd = new SqlCommand(sql, conn);
Int32 count = (Int32)cmd.ExecuteScalar();
string connectionString =
"Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
// Provide the query string with a parameter placeholder.
string queryString =
"SELECT Count(*) from sys.columns";
// Specify the parameter value.
int paramValue = 5;
// Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, connection);
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}",
reader[0]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
use Executescalar() for getting a single element.
using (SqlConnection con = new SqlConnection(ConnectionString)) //for connecting to database
{
con.Open();
try
{
using (SqlCommand getchild = new SqlCommand("select count(*) from table1 ", con)) //SQL queries
{
Int32 count = (Int32)getchild.ExecuteScalar();
}
}
}
Use ExecuteScalar
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
Int32 colnumber = 0;
string sql = "SELECT count(*) FROM sys.columns";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
colnumber = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
You'll want to use the ADO .NET functions in the System.Data.SqlClient namespace. ExecuteScalar is an easy-to-use method when you only want to get a single result. For multiple results, you can use a SqlDataReader.
using System.Data.SqlClient;
string resultVar = String.Empty;
string ServerName="localhost";
string DatabaseName="foo";
SqlConnection conn=new SqlConnection(String.Format("Data Source={0};Initial Catalog={1};Integrated Security=SSPI",ServerName,DatabaseName));
SqlCommand cmd=new SqlCommand(Query,conn);
try
{
conn.Open();
}
catch (SqlException se)
{
throw new InvalidOperationException(String.Format(
"Connection error: {0} Num:{1} State:{2}",
se.Message,se.Number, se.State));
}
resultVar = (string)cmd.ExecuteScalar().ToString();
conn.Close();

Categories

Resources