The only problem with this is it exposes your application to sql injection attack, which is not good.
You want to avoid concatenating SQL whenever possible.
So the solution is to use a parameter like the example below:
SqlConnection conn = null; SqlCommand cmd = null; try { conn = new SqlConnection( CONNECT + "Pooling=False;" ); conn.Open();
// This code below just creates test table and inserts some test values... xsql_noerror( conn, "drop table tblTest" ); xsql( conn, "create table tblTest(f1 varchar(255))" ); xsql( conn, "insert into tblTest(f1) values ('aaa')" ); xsql( conn, "insert into tblTest(f1) values ('bbb')" ); xsql( conn, "insert into tblTest(f1) values ('ccc')" );
// This code demos how to use LIKE with parameter (the safe way to avoid concatenation). cmd = conn.CreateCommand(); cmd.CommandText = "select * from tblTest where f1 like @p1"; // Create parameter @p1 cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@p1", SqlDbType.VarChar, 255); // Set @p1 to matching type for field f1 cmd.Parameters[0].Value = "a%"; // Set parameter value with % at end for matching. SqlDataReader dr = cmd.ExecuteReader(); // Fetch our data reader. while (dr.Read()) { System.Diagnostics.Debug.WriteLine(dr[0].ToString()); } dr.Dispose(); cmd.Dispose(); } catch( SqlException sqlEX ) { System.Diagnostics.Debug.WriteLine( "sqlEX.Number=" + sqlEX.Number ); System.Diagnostics.Debug.WriteLine( "sqlEX.Message=" + sqlEX.Message ); } finally { conn.Dispose(); }
Matt Neerincx [MSFT] |