SQL Like statement not working in Visual Basic - sql

Dim strText As String = tbRefine.Text
Dim sql As String = "SELECT user_name,forename,surname,game_cash,reg_group FROM tblGame WHERE user_name LIKE '" + strSearchText + "' & '*'"
Dim dsRefine As New DataSet
GetDataset(sql, "tblGame", dsRefine)
MsgBox(dsRefine.Tables("tblGame").Rows(0).Item(2).ToString)
This is not working, it crashes and says there is nothing in the dataset.
I know the dataset function works as its worked successfully before.
When i print out the sql statement into microsoft access it works fine. What am i doing wrong

Try this:
"SELECT user_name,forename,surname,game_cash,reg_group
FROM tblGame
WHERE user_name LIKE '%" + strSearchText + "%'"

Try to use the RTRIM() function in your line:
Dim sql As String = "SELECT user_name,forename,surname,game_cash,reg_group
FROM tblGame
WHERE RTRIM(user_name) LIKE '" + strSearchText + "' & '*'"

What about leading or trailing % symbols in your like?
At the moment you will end up with a where clause like:
LIKE 'searchtext''*'
which looks a bit odd (I assume SQL server?).

It's wiser to use SQL parameters as your method is open to SQL injection. The link below will help with how to format the SQL statement. I would also suggest doing it via a store procedure, but hats optional...
http://forums.asp.net/t/1256985.aspx

I think there's one more thing to be mentioned:
the "*" wildcard character works for the "Like" operator in VB/VBA/MS-Access, but not in T-SQL.
The correct wildcard character for the "Like" operator in T-SQL is "%".
That's why this T-SQL statement:
Select... WHERE ... LIKE 'sText*'
returned no data without any syntax error in MS-SQL(using T-SQL), but works in MS-Access.

Related

double where statement in SQL and ASP

I am a little lost on how to incorporate TWO Where in my sql statement in my asp.
I am trying to get the userID and password entered previously and compare it with what I have in my database created on SQL:
I think my problem comes from my double quotation and single quotation.
UserID is a number in my database and Password is a short text.
var mycon = new ActiveXObject("ADODB.Connection");
var myrec = new ActiveXObject("ADODB.Recordset");
mycon.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\Omnivox.mdb");
var txtpassword = Request.QueryString("txtpassword");
var txtuserID = parseInt (Request.QueryString("txtuserID"));
var sql;
sql = "SELECT UserID, UserPassword FROM UserOmnivox WHERE UserID=" +txtuserID+ " AND UserPassword='" + txtpassword + "';";
myrec.Open(sql, mycon);
thank you
UPDATE: It is still not working. The error massage is : no value given for one or more required parameters for the line myrec.Open(sql,mycon)
Change
sql = "SELECT * FROM UserOmnivox WHERE UserID=" +txtuserID "AND UserPassword="'+txtpassword';
to
sql = "SELECT * FROM UserOmnivox WHERE UserID=" +txtuserID + " AND UserPassword='"+txtpassword+"'";
If you'd done any kind of basic debugging, like LOOKING at the query string you're generating, you'd have seen this:
sql = "SELECT [..snip..] UserID=" +txtuserID "AND UserPassword="'+txtpassword
^^--- no space
^--- missing +
which produces
SELECT .... UserID=1234AND userPassword
^^---syntax error, no such field '1234AND'
And then, yes, your quotes are wrong too
sql = "SELECT ... UserID=" +txtuserID "AND UserPassword="'+txtpassword
^------------------^-- one string
^-----------------^-- another string
^---???
It should be
sql = "SELECT * FROM UserOmnivox WHERE UserID=" +txtuserID + " AND UserPassword='" + txtpassword + "';";
I find another more flexible solution is better. Sometimes based on conditions you have one where condition, in others you have zero, and in others you have two. If you go down these paths they don't solve that issue. The following does.....
Some sql query
where 1=1 -- ## A condition that will always be true and does nothing to your query.
and first optional where clause
and second optional where clause
This way if you don't have the first where clause in a given situation but you do have the second you are not missing the words "where". You always have the where and you optionally add any array of "and" parts to your where statement. 100% flexibility in this method works for all challenges. Plus it is easier to follow code once you get past the wtf is this 1=1 nonsense reaction.

Quoting problems with a string query in sql

I am trying to make a query using the LIKE operator
String camp= nomePesquisa.getValue();
String ql = "select from pessoal where nome_Pessoa like ""'%"+camp+"%'" "";
and it gives the following error
Multiple markers at this line
- Syntax error on token """", delete this
token
There is a basic mistake that causes all the issues: you don't use parameterized queries. This will a) secure your code against SQL injection, and b) make your SQL easier to write.
In my preferred programming language, C#, it would look like this:
"select from pessoal where nome_Pessoa like #name"
Where #name is the name of the parameter you have to pass in.
It seems according to your code you are using Java. This might help you in that case.
try this
String ql = "select * from pessoal where nome_Pessoa like '%"+camp+"%'+ ";
you've put to many quetas, but if you need them to bee in string for some reason, you should escape them \".
P.S. you forgot to type what you wanna select
Select * FROM table or SELECT col1,col2 FROM TABLE
P.S.S. don't put parameters in query like that, because it is an easy way for Query Injection.
Remove all the " from that line:
String ql = "select from pessoal where nome_Pessoa like '%"+camp+"%'+ ";
You aren't concatenating anything there.
Please use the following to remove the unnecessary quotes:
String ql = "select from pessoal where nome_Pessoa like '%"+camp+"%'+ ";
Also, you can use some escape characters.
You can simply write it as
String ql = "select from pessoal where nome_Pessoa like '%" + camp + "%'";
Change the following code
String ql = "select from pessoal where nome_Pessoa like '%"+camp+"%'+ ";
You missed the plus operator

Ole DB statement runs in Access but not in Visual Studios

I have the following statement and it returns my desired result in Access however in Visual Studio, I receive an error saying "; expected", what could be the problem?
var query = "SELECT Count(*) FROM usersTable WHERE (((usersTable.[uDateCreated]) Between DateAdd("d",-2,Now()) And Now()))";
You need to escape your quotes inside your string:
" .. Between DateAdd(\"d\",-2 .. "
^ ^ escape the quotes
You're using a quotation mark in your query, which is ending the string. Use apostrophes around d instead:
var query = "SELECT Count(*) FROM usersTable WHERE (((usersTable.[uDateCreated]) " & _
"Between DateAdd('d',-2,Now()) And Now()))"
Specifically:
DateAdd('d',-2,Now())
I think your problem is that you have " (quotes) in your string without escaping them. I donut know which language you are using, but for many you escape with \ (backslash), then your string would read DateAdd(\"d\",

Matching text string on first letter in SQL query

SAMPLE CODE:
Dim sql As String = "SELECT * FROM " + tblName + " WHERE needsTranslation = 'True' AND dataText LIKE " & "'" & alpha & "%" & "'" & " ORDER BY dataText;"
da = New SqlDataAdapter(sql, strConnection)
OP:
I would like to create a SQL query that returns all records when the first letter of a string matches my variable. I am coding this in an ASP.net code behind page in vb.net.
SELECT * FROM " + tblName + " WHERE textData = ' & alpha & "
In this exmample textData is a string of text and alpha is a single letter a through z or A through Z.
I don't need the criteria to be case sensitive, but I do need only the first letter of textData to match alpha.
I have tested the LIKE comparator and it does not return all records that begin with alpha.
What is the best way to do this? Any and all help will be appreciated.
thanks again,
The LIKE operator is what you'd want to use, but you have to use the % wildcard character like so:
SELECT * FROM MyTable WHERE textData LIKE 'a%'
SQL has sub-string operator SUBSTR() or SUBSTRING()
select * from tableName where substr( textData ) in ( 'A', 'B', 'C', ... );
I couldn't add to the comments on one of the other posts, but I'll strongly second the need to use a parameterized query for these reasons (you can include usage of the like operator with the wildcard % like the other answer correctly summarized to answer your question):
It will protect you from making mistakes with single quotes, especially if the user enters a search string that includes them
(they will cause your query to fail).
It protects you from SQL injection exploits. Example, a user were able to input the value of the variable "alpha" in the above
example they could enter something like:
'; DELETE FROM ;
If the user you were using had excessive database rights, they could
wreak all kinds of havoc (or they could potentially get access to
data they shouldn't have access to).

Split a String in Microsoft Access SQL for use with a command parameter

I am using Microsoft Access 2000, and need to pass in a parameter that is a comma-delimited string. The comma-delimited string is for an IN clause of the where statement. An example of this would be:
SELECT * FROM Table1 WHERE Field1 IN (#MyValues)
where #MyValues might be something like 1,2,3
However, when I pass in 1,2,3 the Access parameter doesn't seem to accept the input. Is there a good split string function in Access SQL that will solve this issue? Or is there another way of tackling this problem?
For reference on what I am doing, I am trying to use parameterized SQL in .NET to get a result set.
EDIT:
Below is an example of some simplified .NET code that would call this query:
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Table1 WHERE Field1 IN (#MyValues)");
cmd.Parameters.Add("#MyValues","1,2,3");
What about this:
SELECT * FROM Table1 WHERE #MyValues Like "%" & Field1 "%"
This should check to see if the value in the field is included as a substring of your #MyValues parameter. Now, this could be problematic if any of the individual values in #MyValues are substrings of each other:
SELECT * FROM Table1 WHERE "2, 5, 10" Like "%" & Field1 "%"
In that case, "1" in Field1 would match, but it shouldn't. So, it might be that you'd need to format the numbers or delimit them some other way, such as:
SELECT * FROM Table1 WHERE " 2 5 10 " Like "% " & Field1 " %"
Or, alternatively:
SELECT * FROM Table1 WHERE ", 2, 5, 10," Like "%, " & Field1 ",%"
I'm not sure how this would perform, but it at least would allow parameterization.
At first, your question looked a little familiar. Then it started looking REALLY familiar. Then I realized I had the same question not long ago. My solution was to toss the parameters into this function:
Public Function IsIn( _
ByVal value As Variant, _
ParamArray theset() As Variant) _
As Boolean
Dim i As Long
For i = LBound(theset) To UBound(theset)
If value = theset(i) Then
IsIn = True
Exit Function
End If
Next
End Function
In your sample SQL code, you could do something like:
SELECT * FROM Table1 WHERE IsIn(Field1,array(1,2,3))=true;
(Like you, I also think that a procedure like this one should have been built into Access. Perhaps it is in 2007 or 2010.)
Edit
See Is there a NotIn("A","B") function in VBA?
Can you put them in another table and do a join?
If you don't want to create another table, that's ok. What does your ADO code and query syntax look like?
From your edited code above, I don't think you need to use the cmd object's parameters collection. Just modify your sql to embed your parameter values:
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Table1 WHERE Field1 IN (1,2,3)");
You would use the .parameters collection if you had a parametrized query in the mdb, which you don't. Your sql is in source code.