AndyDB
AndyDB

Reputation: 431

Creating a parametrised, MySQL query with wildcards

I want to populate a datagrid using a parameter based query. However, I want to have the ability to enter multiple parameters that may contain wildcards. However, the following test query isn't correct.

Any ideas where I'm going wrong?

SELECT `Customer ID`, `Company Name`, `Address Line 3` FROM XTest.all WHERE `Company Name` LIKE '%'+@Company+'%' ORDER BY `Company Name`;

Upvotes: 1

Views: 674

Answers (2)

Hassan
Hassan

Reputation: 5430

You need to enclose column names in "" double quotes (depends on the setting of SQL Mode).

Please check this link and follow the answer of @DRapp. Here is link: mysql parameterized query in ASP.NET

As per the answer you need to use ? instead of @.

Try this:

SELECT `Customer ID`, `Company Name`, `Address Line 3` 
        FROM XTest.all 
        WHERE `Company Name` LIKE  concat('%',? + "Company",'%') 
        ORDER BY `Company Name`;

objCommand.Parameters.AddWithValue("?Company", "CompanyValue");

Upvotes: 1

Ravinder Reddy
Ravinder Reddy

Reputation: 24002

string company = "%" + your_criteria_on_company + "%";

string sql = "SELECT 
                `Customer ID`, `Company Name`, `Address Line 3` 
              FROM XTest.all 
              WHERE 
                `Company Name` LIKE @Company 
              ORDER BY `Company Name`";

SqlCommand sqlCommand = new SqlCommand( sql, dbConnection );
sqlCommand.Parameters.AddWithValue( "@Company", company );

' add more of your code here
' and then
sqlCommand.Prepare();
MySqlDataReader resultSet = sqlCommand.ExecuteReader();

Refer to:

Upvotes: 2

Related Questions