SQL to Query text in access with an apostrophe in it - sql

I am trying to query a name (Daniel O'Neal) in column names tblStudents in an Access database, however Access reports a syntax error with the statement:
Select * from tblStudents where name like 'Daniel O'Neal'
due to the apostrophe in the name.
How do I overcome this?

You escape ' by doubling it, so:
Select * from tblStudents where name like 'Daniel O''Neal'
Note that if you're accepting "Daniel O'Neal" from user input, the broken quotation is a serious security issue. You should always sanitize the string or use parametrized queries.

When you include a string literal in a query, you can enclose the string in either single or double quotes; Access' database engine will accept either. So double quotes will avoid the problem with a string which contains a single quote.
SELECT * FROM tblStudents WHERE [name] Like "Daniel O'Neal";
If you want to keep the single quotes around your string, you can double up the single quote within it, as mentioned in other answers.
SELECT * FROM tblStudents WHERE [name] Like 'Daniel O''Neal';
Notice the square brackets surrounding name. I used the brackets to lessen the chance of confusing the database engine because name is a reserved word.
It's not clear why you're using the Like comparison in your query. Based on what you've shown, this should work instead.
SELECT * FROM tblStudents WHERE [name] = "Daniel O'Neal";

Escape the apostrophe in O'Neal by writing O''Neal (two apostrophes).

...better is declare the name as varible ,and ask before if thereis a apostrophe in the string:
e.g.:
DIM YourName string
YourName = "Daniel O'Neal"
If InStr(YourName, "'") Then
SELECT * FROM tblStudents WHERE [name] Like """ Your Name """ ;
else
SELECT * FROM tblStudents WHERE [name] Like '" Your Name "' ;
endif

How about more simply: Select * from tblStudents where [name] = replace(YourName,"'","''")

I was looking for how to find all records where there was an apostrophe in the column value. Using the double ' suggested by #Alex K, I came up with
SELECT * FROM [table] WHERE ([column] LIKE '%''%')
Adding it to this question for others who maybe looking for the same resolution.

Related

How to escape single quotes in Firebird 2.5 in where clause of select statement

How do I get this to work?
select * from table where column like '%situation = 'C'%'
To escape an apostrophe you need to double it see manual
select * from table where column like '%situation = ''C''%'

How do i match text excluding difference between brackets in SQL server?

I've an audit log table that has a series of strings like
"Some Text[details]more text"
the pattern before and after the [details] indicates what the audit trail entry type is. The text in the bracket indicates what it is for. I want to create a query to only find the audit entries i'm after. I thought to use the following like "Some Text[%]more text" but it does not seem to work
When I run the below query it retrieves the expected results + more
select top 1000 *
from Table
where NAME like 'Some Text%'
When I try
select top 1000 *
from Table
where NAME like 'Some Text[%'
Nothing comes back is the
Brackets have a special syntactic meaning in regular expressions. So you need to escape the bracket if you want to use it in your query:
select top 1000 *
from Table
where NAME like 'Some Text[[]%'
Special characters can be escaped by placing them inside brackets. In this case, the opening bracket itself needs to be placed inside brackets, i.e. [[]
try the t-sql code below:
create table dbo.tblTest (ID int IDENTITY(1, 1), strings varchar(200))
insert dbo.tblTest
select 'i have to find this text excluding [these strings inside the brackets]'
union all select '[don''t include these texts inside the brackets]. but include these!'
union all select 'why can''t i search for these, but [not these]? nothing seems to work when brackets are involved. :('
select *
from dbo.tblTest
DECLARE #stringToSearchFor VARCHAR(200) = 'nothing seems'
SELECT t.*
FROM dbo.tblTest t
JOIN
(SELECT nobrackets.*
FROM
(SELECT cleanString = REPLACE(t.strings, SUBSTRING(t.strings, CHARINDEX('[', t.strings), CHARINDEX(']', t.strings) - CHARINDEX('[', t.strings) + 1), '')
, t.ID
FROM dbo.tblTest t) noBrackets
WHERE noBrackets.cleanString LIKE CONCAT('%', #stringToSearchFor, '%')) tNoBracket ON tNoBracket.ID = t.ID
If you will take sometime here in stackoverflow, a lot of post will answer your question.. Please see below.
You need to use [ ] bracket to surround the text with special character..
The query now look something like:
select top 1000 *
from Table
where NAME like '[Some Text[]%'
SQL LIKE CONDITION
SQL Server LIKE containing bracket characters
select top 1000 *
from Table
where NAME like 'Some Text[[%] more text'
or
select top 1000 *
from Table
where NAME like 'Some Text![%] more text' ESCAPE '!'
How can I escape square brackets in a LIKE clause?

incorrect syntax error near ,

I have recently changed my database from access to a .mdf and now I am having problems getting my code to work.
One of the problems im having is this error "incorrect syntax near ,".
I have tried different ways to try fix this for example putting brackets in, moving the comma, putting spaces in, taking spaces out but I just cant get it.
I would be so grateful if anyone could help me.
My code is:
SqlStr = "INSERT INTO UserTimeStamp ('username', 'id') SELECT ('username', 'id') FROM Staff WHERE password = '" & passwordTB.Text & "'"
Assuming you're looking for username and id columns, then that's not proper SQL syntax.
The main issues are that you're column names are enclosed in single quotes and in parentheses in your select. Try changing it to this:
SqlStr = "INSERT INTO UserTimeStamp (username, id) SELECT username, id FROM Staff WHERE password = '" & passwordTB.Text & "'"
That will get sent off to SQL like this:
INSERT INTO UserTimeStamp (username, id)
SELECT username, id
FROM Staff
WHERE password = 'some password'
There are a number of issues I potentially see.
Column names shouldn't be quoted, i.e. INTO UserTimeStamp('username','id') should be INTO UserTimeStamp(username, id)
Column fields, unless literal strings, shouldn't be quoted either. i.e. SELECT ('username','id') should be SELECT username, id.
You are putting yourself at risk for T-SQL injection by quoting your parameter like that. You should consider using a stored procedure, or use a well tested function to secure your parameters if you are doing ad-hoc queries.
SqlStr = "INSERT INTO UserTimeStamp (username, id) SELECT username, id FROM Staff WHERE password = " + MyQuoteFunction(passwordDB.Text);
Try wrapping column names in square brackets like so:
INSERT INTO employee ([FirstName],[LastName]) SELECT [FirstName],[LastName] FROM Employee where [id] = 1
Edit: Also drop the parentheses surrounding the selected fields.

String concatenation not working as expected in SELECT statement

I'm using MS Access to work with an SQL Server database through an ODBC connection on Windows 7.
The ultimate goal is to append a string literal to one of the fields for a subset of rows. Initially, though, I'm just trying to do a SELECT so I can make sure I have everything correct. I'm having trouble trying to append a string literal to the field.
The below simple SQL works well.
SELECT Name FROM Customers WHERE CustomerType = 1;
Next step was to try and modify the displayed name slightly.
SELECT Name, 'PREFIX' & Name FROM Customers WHERE CustomerType = 1;
The above also worked. Then I tried the following.
SELECT Name, Name & 'SUFFIX' FROM Customers WHERE CustomerType = 1;
This does not work. The output shows just the Name field with nothing appended. I looked around and found SQL Server seems to support CONCATENATE('a' + 'b'). I tried using that in the query but it failed with an error from Access about there not being a CONCATENATE function.
I also tried double quotes instead and + instead of &.
Seems odd that the prefix case worked and the suffix case did not.
The eventual goal, again, would be to construct something like the below.
UPDATE Customers SET Name = Name & 'SUFFIX' WHERE CustomerType = 1;
This would append a suffx to a text field for a subset of rows in the table.
Any ideas?
In SQL Server, & is for binary masks. You want the + operator
UPDATE Customers
SET Name = Name + 'SUFFIX'
WHERE CustomerType = 1;
I don't know where you got CONCATENATE from - There is a CONCAT function in SQL 2012, but nothing like that in any other version
My impression is you have an Access query with Customers as an ODBC link to a SQL Server table. If that is correct, either of these 2 query versions should work.
SELECT
[Name],
[Name] & 'SUFFIX'
FROM Customers
WHERE CustomerType = 1;
SELECT
c.Name,
c.Name & 'SUFFIX'
FROM Customers AS c
WHERE c.CustomerType = 1;
The reason for this suggestion is that Name is a reserved word. One thing that makes reserved words frustrating is that you don't know when they will bite you. A reserved word might not cause trouble in one context but cause the same SQL statement to fail in another context. Enclosing the name in square brackets or qualifying the name with an alias (or the table name) avoids confusing Access' db engine.
Try this for your UPDATE.
UPDATE Customers
SET [Name] = [Name] & 'SUFFIX'
WHERE CustomerType = 1;

How to give entry in the where clause when we use it in webpages?

According to the user's input I want to select the record from the database. This is my code:
<%
String jempid=request.getParameter("empid");
out.println(jempid);
int intempid=1223;
Connection conn=null;
String url="jdbc:mysql://localhost/employees";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn=DriverManager.getConnection(url,"root","");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("select * from empdetails where empnum=jempid");
%>
It throws the following error
javax.servlet.ServletException: java.sql.SQLException: Unknown column 'jempid' in 'where clause
It's a bad idea to construct SQL using string concatenation - you're just opening yourself up to a SQL injection attack -- ESPECIALLY considering that you're getting the value of "empid" directly from the request. Yikes!
A better approach is use a parametrized query such as below:
PreparedStatement st=conn.prepareStatement("select * from empdetails where empnum=?");
st.setString(1, jempid);
ResultSet rs=st.executeQuery();
Also you should check that jempid is not null.
Here is your select statement:
select * from empdetails where empnum=jempid
jempid is hardcoded instead of being used as a variable. This will never work unless you change it to the variable value entered by the customer.
alter to:
"select * from empdetails where empnum=" + CleanseUserInput(jempid)
and you're good to go.
That looks like too much code in a jsp page....
that said:
... empnum='"+jempid+"');" ......
And also when you are done be sure to close the db too
yes sometimes it throws an error of unkown column say for example we have table bikes
so lets say we have a query like select * from bikes where bikename=hayabusa;
if you will hit this query than it might throw an error like unknown column so the best thing you should take care is quote your value ehich you are giving in where clause so the correct way goes as select * from bikes where bikename='hayabusa';
Try this:
ResultSet rs=st.executeQuery(
"select * from empdetails where empnum=" + jempid);
You need to put the value of jempid into the string, not the text "jempid".
ResultSet
rs=st.executeQuery("select * from empdetails where empnum=" + jempid + ";")
"select * from empdetails where empnum="+jempid
But you really want to protect this against SQL injections!
In contrast to other responses, why not use a PreparedStatement?
Basically, you'll have to code like this:
PreparedStatement st=conn.prepareStatement("select * from empdetails where empnum=?");
st.setString(1, jempId);
ResultSet rs=st.executeQuery();
The reason you should use PreparedStatements is because of SQL Injection issues. For example, using the code you posted in the question, a hacker can always type "1;delete * from empdetails" in the textbox from which you select jempid.
Thus the final query formed would be
select * from empdetails where empnum=1;delete * from empdetails
which would result in all data in empdetails getting deleted.
So always use PreparedStatements!!
where should have the input within " ". Like this:
"select * from empdetails where empnum = "jempid";
Hence this should work:
ResultSet rs = st.executeQuery("select * from empdetails where empnum=" +"'"+ jempid+"'");