I want to use a select statement to find if there is a record that already exists. I\'ve put the code below but it throws an error at the dReader = comm.ExecuteReader(); and i\'
Change your ==
to =
. That is invalid SQL as it is.
Also if txtID.Text is non-numeric then it needs to be in single quotes. You should not be constructing your SQL like this, instead use a parameter:
comm.CommandText = "SELECT * FROM Customers WHERE CustomerID = @CustomerID";
comm.Parameters.AddWithValue("CustomerID", txtID.Text);
C# using statement
SQL reference
SQL injection (why you should parameterize your queries)
You are using invalid SQL. You name to change "==" to "=".
You should also consider wrapping your IDisposable
objects in using
statements so that unmanaged objects are properly disposed of and connections are properly closed.
Finally, think about using parameters in your SQL, instead of concatenating strings, to avoid SQL injection attacks:
string connString = @"Data Source=KIMMY-MSI\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
string sql = "SELECT * FROM Customers WHERE CustomerID = @CustomerID";
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand comm = new SqlCommand(sql, conn))
{
comm.Connection.Open();
comm.Parameters.AddWithValue("@CustomerID", txtID.Text);
using (SqlDataReader dReader = comm.ExecuteReader())
{
if (dReader.HasRows == true)
{
Response.Write("Exists");
}
}
}
Change this line:
comm.CommandText = "SELECT * FROM Customers WHERE CustomerID == " + txtID.Text;
To this line:
comm.CommandText = "SELECT * FROM Customers WHERE CustomerID = @id";
comm.Parameters.AddWithValue("id", int.Parse(txtID.Text));
Assuming that your customer id is int on the database.
The equals operator in SQL is just a single =
.
Also, you really shouldn't be concatenating SQL queries like that, you are just opening yourself up to SQL Injection attack. So change it to be like this:
comm.CommandText = "SELECT * FROM Customers WHERE CustomerID = @CustomerId";
comm.Parameters.AddWithValue("@CustomerId", txtID.Text);
See Stop SQL Injection Attacks Before They Stop You on MSDN.
It looks like your command has an issue:
SELECT * FROM Customers WHERE CustomerID == 1
In SQL you don't need to use the == operator to ensure something is equal to another.
Try:
SELECT * FROM Customers WHERE CustomerID = 1
In addition, you might want to read up about SQL Injection, the way you are binding the value is directly from a textbox value. This has a huge security hole which could lead to arbitrary sql command execution.