C# - Web Site - SQL Select Statement

后端 未结 5 1991
深忆病人
深忆病人 2021-01-24 16:29

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\'

5条回答
  •  广开言路
    2021-01-24 16:32

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

提交回复
热议问题