SQL OleDb provider string parameter - how does it work? - sql

I'm using .xsd dataset visual tool to help me build SQL DAL. Unfortunately, the server I'm connecting to is SQL Server 2000. So from VS 2010 the only provider I foud was OLE DB provider. This has some disadvantages. E.g. ? instead of named parameters etc.
I have a problem with querying for text part. Query in designer looks like this:
SELECT * FROM table WHERE nvarcharcolumn1 LIKE '%' + ? + '%'
This works fine from designer, when I insert value for this ? as %. % doesn't work and neither does ''.
But after I use xsd "Preview Data" it doesn't work with any of these values. And when called from C# code it doesn't work either.
How can I use string parameters correctly, when I want to filter by part of string and eventually allow omission of this parameter (one possibility is to create a query for each combination of not-required parameters but it's too much redundant code IMO).

SELECT * FROM table WHERE nvarcharcolumn1 LIKE '%<part of a string you want to search>%'

The way you have the string setup will open you up to SQL-injection. You should really use parameters something like
OleDbCommand cmd = new OleDbCommand( "SELECT * FROM table WHERE nvarcharcolumn1 LIKE ?", yourConnection );
cmd.Parameters.AddWithValue( "QmarkPlaceHolder", "%" + ValueLookingFor + "%" );
then continue execution of your query

Related

How To Make MSSQL Ignore The " ' " Inside The Value User Is Giving?

I am doing an insert operation from C# and everything goes well except that one insert statement where the user writes something like "roomie's books" in a value because of the ' operator. How can i make Sql ignore the ' inside values?
They're called parameterized queries.
You probably have something like this:
string sql = "SELECT * FROM Bookstores WHERE StoreName = '" + txtStoreName.Text + "'";
That is very bad! Imagine if the user had typed in something like ';DROP TABLE Bookstores; -- instead of roomie's books.
What you need to do is this:
string sql = "SELECT * FROM Bookstores WHERE StoreName = #StoreName";
using (var cn = new SqlConnection("connection string here"))
using(var cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.Add("#StoreName", SqlDbType.NVarChar, 50).Value = txtStoreName.Text;
}
That assumes you're using raw ADO.Net objects. If you have an ORM like EntityFramework or Dapper the mechanisms for using parameters will look a little different.
The important thing is, the txtStoreName.Text value is NEVER directly substituted into the SQL code, not even on the server. It's sent to the server separately from the SQL, so there's no possibility of ever contaminating the SQL with user input. You need to fix EVERY QUERY in your application work this way; anything less is practically begging to get hacked, and this is one of those things that's too important to even do wrong for learning or prototypes.
This also tends to perform better, because it allows the server parse the query code once and cache the execution plan.
Joel gave the right answer, but for completeness' sake, I would would like to add that you can escape the ' character in a string literal in T-SQL by adding another one.
So, for instance
INSERT INTO BookStores ([Name]) VALUES ('Roomie''s Books')
But like Joel said, you should never do this, especially for user-entered data, and use parameters when passing data to SQL Server from code instead.

SQL error using a wild card from a database

Basically trying to use a wildcard SQL to select and fields that hold the data from txtclass in the homework column of the database. But for some reason what i have done is causing an error. (im am using VB.net)
The standard wildcard character is the % not the *. It seems that you have taken this query directly from the designer of MS-Access (and perhaps the * is supported by this database system also from ADO.NET).
However there is a bigger problem
The wildcard should be part of the string to match against the LIKE not outside the single quotes
... LIKE '%" + txtclass.Text + "'))";
Said that you should start immediately to use a parameterized query instead of string concatenation if you want to avoid Sql Injection and parsing problems
Use like=* '%txtClass.text%' instead of like=' &txtClass.text&'
Try your SQL statement as:
SELECT tblQuiz.QuizID, tblQuiz.Classhomework FROM tblQuiz WHERE
tblQuiz.Classhomework LIKE '%' + pupilclass + '%';

Talend: Query Database with Strings/Parameters already defined

How can I perform a Query to my Database (using tOracleInput), like a Select, and use Strings that are already defined as parameters in other components, for example in a 'tFlowToIterate' ?
For example: "SELECT * from TABLE_X where FIELD_X= ? ;"
My '?' is the variable that comes from my tFlowToIterate component (foo). I already tried with (String)globalMap.get("foo"), and other similar forms...
Thanks
[Talend Open Studio for Data Integration v5.3.1;
DB: Oracle]
You answered by yourself. tOracleInput component accepts the query as parameter. This is a very boring java String, no more, no less. This means that if you want to use a globalMap element inside a query, you just need to do a java String concatenation. Something like that:
"SELECT * from TABLE_X where FIELD_X='" + (String)globalMap.get("foo") + "'"
but this won't work (look carefully at the quotes):
"SELECT * from TABLE_X where FIELD_X='(String)globalMap.get("foo")'"
Keep in mind that if you write a query using string concatenation and external vars, the query editor will probably going to mess all the quotes, generating a broken query.
As a general advice, I never suggest to use the "*" operator inside a database input component like tOracleInput. Talend has a fixed-scheme structure that is generated at compile time. This means that if one day you'll add a column to TABLE_X, your ETL will going to fail.
A more robust solution is the following:
Write down your query with the * operator
Click "Guess Schema" to retrieve the table schema and put in your component metadata
Now click "Guess Query" to explicitely rewrite your SELECT
Fix the query (ie. WHERE conditions,...) if needed
You just need to concatenate it with your variable.
So in your case it would look like:
"SELECT *
FROM TABLE_X
WHERE FIELD_X = '" + (String)globalMap.get("foo") + "'"

Use of Like * Works in MS-Access but Not VBA

I have a simple query but am running into problems using LIKE in VBA. My SQL string in VBA is:
stsql1 = "Select Top 25 data.* from data where data.Description Like ('*') "
When I run this sql string in my VBA code I get no records returned, but if I copy/paste the same string into a query in SQL View in MS Access, the query returns the values I expect. Is there a trick to using the "Like" syntax in VBA?
I can provide additional code and a small version of the database if that would help.
For SQL, the database engine will accept either single or double quotes as text delimiters. So either of these 2 WHERE clauses will work.
WHERE some_field Like '*'
WHERE some_field Like "*"
VBA however only accepts double quotes as text delimiters, so you would have to use the second form.
Two other points about your SELECT statement:
Select Top 25 data.* from data where data.Description Like ('*')
TOP [number] is arbitrary without an ORDER BY clause
You don't need parentheses surrounding your Like pattern ... you can use Like "*"
If your VBA code is using ADO with that SELECT statement, you must change the wild card character from * to % ...
WHERE data.Description Like '%'
In ADO/VBA, you have to use % instead of * as the wildcard. I ran into this a couple times in the past ....
Realize that there are at least 2 (yes two!) LIKE operators here.
One is the LIKE operator of VBA.
The other is the LIKE operator of the SQL of the database you are attached to.
The usual wildcards in SQL are % (for any # of any characters) and _ (for one of any character).
Know also that MS Access can open databases that aren't Access; it could be Microsoft SQL Server, or Oracle or IBM DB2. (BTW, the database that is normal for Access is called Microsoft JET.) You may be sheltered from that truth when you create a Query object in Access - in that circumstance, you are using JET SQL even when it's a linked table you are querying.
However, under VBA, when using either DAO or ADO, you're talking directly to whatever the database system happens to be, in which case you MUST use the SQL of that specific system.
OK, short answer: Use % like cularis said.
I can't add a comment, but I think it would be worth noting that you have to use % even if you are querying MS Access.
(example: Outlook VBA runs query on an Access database. The proper query is select * where user like '%bob%', even though this query would not work if plugged directly into an MS Access query).

TableAdapter FillBy Query with parameters doesn't work with LIKE operator

Banging my head against a wall here. I have a query that looks like this.
SELECT FirstName, LastName, Address
FROM Members
WHERE FirstName LIKE 'JOE%'
That works absolutely fine in query wizard and the DataTablePreview data window. However, when I do this.
SELECT FirstName, LastName, Address
FROM Members
WHERE FirstName LIKE ?
I get nothing when I run the fillby method. If I change the LIKE to =.
SELECT FirstName, LastName, Address
FROM Members
WHERE FirstName = ?
Everything works great. I need to get LIKE working though so I can wildcard search.
I'm using the SQL server OLE db connections if that means anything.
UPDATE
Using the LIKE operator doesn't work at all. When I just swap out = for LIKE. Nothing is returned.
You'll need to convert your query to :
WHERE FirstName LIKE '%' + ? + '%'
If you pass % within the parameter itself, I think it will interpret it as a string value rather than a wildcard and just work the same as FirstName = 'JOE%'
I had this problem. The query worked in the query builder and then when previewing it in the table adapter it failed.
I changed the SQL to be LIKE LTRIM(RTRIM(#string))
And then I put the % in the string that I was sending. The table adapter was sending the full string in the parameter, including spaces, even if the input was trimmed. This meant that the query would never find the data because of the spaces
Can you not add the % to the param field?
Found at
Using 'like' in TableAdapter SQL
statement with parameter
using the LIKE statement in a table
adapter
So it turns out that something in the OLEDB connection was hosed up. When I created a new connection and a new table adapter, everything started working fine.
EDIT
What I actually did was use the SQL server adapter instead of the SQL server OLEDB adapter.
DB