C# - Web Site - SQL Select Statement

风流意气都作罢 提交于 2019-12-02 04:02:40

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);    

More Info

C# using statement

SQL reference

SQL injection (why you should parameterize your queries)

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.

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.

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");
        }   
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!