Question

I am trying to execute a SQL statement with a where clause which looks like

 string s2 = "Select * from idtyfile where oysterid=" + id ;
 SqlCommand da2 = new SqlCommand(s2, con); or 
 SqlAdapter da2 = new SqlAdapter(s2, con);

Both of these are failing when I am trying to execute them

da2.ExecuteReader();

the data in ID looks like

ID
43PCOU5T
ZP6RAEJ0

For some reason both of these queries are failing on these kind of data.

Était-ce utile?

La solution

You are missing the single quotes in your select command which is what is making your original SELECT fail. However I would like to note that you should always parameterize and encapsulate your SqlCommand / SqlConnection in a using statement. The following would be a cleaner more secure way to solve your problem.

        string s2 = "Select * from idtyfile where oysterid=@id";
        DataTable myDataTable = new DataTable();

        using (SqlConnection conn = new SqlConnection(myConnectionString))
        using (SqlCommand cmd = new SqlCommand(s2, conn))
        {
            cmd.Parameters.AddWithValue("@id", id);
            conn.Open();
            myDataTable.Load(cmd.ExecuteReader());
        }

For some educational resources, you should look at the following links.

MSDN Reference for the using keyword

MSDN Reference for SqlCommand -- Look at the Parameters property.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top