So I'm making a program that takes user input from a GUI as a parameter. How do I handle it if the user inputs a word or sentence with an apostrophe?
I'm using it to input something into a database, so for example:
INSERT INTO users (firstname, lastname) VALUES ('"+firstNameString+"', '"+lastNameString+"')
If the user's name was something like John O'Neill, this would throw an error. How do I handle that apostrope, given that I can't control what users may input?
In order to avoid problems like this use PreparedStatements. Typically your code will look something like this:
....
PreparedStatement ps = null;
try {
ps = connection.prepareStatement("INSERT INTO users (firstname, lastname) VALUES (?,?)");
ps.setString(1,firstNameString);
ps.setString(2,lastNameString);
int result = ps.executeUpdate();
...
To add escape sequence you can use '
in Oracle, If you want to escape '
then add '''
First '
is the starting of String Second '
escapes third char in our case that is '
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.