Suppose I have an execquery statement like this:
db1.execSQL("insert into "+TABLE_NAME+" values('"name"')");
where name is a string variable which contains an apostrophe. For example:
name = "tom's database";
In this case, I get an SQLITEexception near this statement. I am certain that this is because of that single quote.
How to modify this such that the statement does not cause a crash and the name get stored in the db with the single quote intact?
I read online that every such single quote has to be prefixed by another single quote.
Can someone provide the code for the same?
Duplicate question. Check How to escape unsupported character in SQLite on Android?
Use
String escapedName = DatabaseUtils.sqlEscapeString(name);
db1.execSQL("insert into "+TABLE_NAME+" values('" + escapedName + "')");
See http://developer.android.com/reference/android/database/DatabaseUtils.html#sqlEscapeString%28java.lang.String%29
Escaping the special character in the string literal works but generally it's an error prone approach. It's better to use ? placeholder and bind arguments, like this:
db1.execSQL("INSERT INTO " + TABLE_NAME + " VALUES (?)", new String[] { name });
or use insert() with ContentValues which does essentially the same.
You forgot:
To double the string apostrophes (since a apostrophes are the SQL string delimiters).
To add the + in the INSERT string to properly add the variable.
So, I'd change the above INSERT statement to:
db1.execSQL("INSERT INTO " + TABLE_NAME + " VALUES ('" + name.replace("'", "''") + "')");
You can use "PrepareStatement" to avoid problems
SQLiteStatement p = db1.compileStatement("insert into "+TABLE_NAME+" values(?)");
p.bindString(1, name);
p.execute();
Other form:
ContentValues values = new ContentValues();
values.put("name", name);
db1.insert(TABLE_NAME, null, values);
Related
I'm trying to organize a search function on the site, using the Spring-jdbc NamedParameterJdbcTemplate.
public List<PhoneEntry> searchPhoneEntries(String search, String username) {
String SQL = "select * from entries, users where users.enabled=true " +
"and entries.username=:username " +
"and concat(secondName, firstName, patronymic, mobile, tel, " +
"address, entries.email) like ('%:search%')";
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("username", username);
params.addValue("search", search);
return jdbcTemplate.query(SQL, params, new PhoneEntryMapper());
}
But I get an empty list and have no any error.
When using a simple concatenation:
"...like '%" + search + "%'";
it working properly, but as I understand it is not safe.
I tried also add '%' symbols in parameter:
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("username", username);
params.addValue("search", "'%" + search + "%'");
return jdbcTemplate.query(SQL, params, new PhoneEntryMapper());
But it doesn't work too.
The solution is to add the parameter without quotes
params.addValue("search", "%" + search + "%");
and in the SQL string write
String sql = "... like :search";
Your first approach ('%:search%') did not work since named parameters are not recognized within string literals.
The second approach params.addValue("search", "'%" + search + "%'"); did not work since now the quotes were part of the like string, therefore asking Mysql to look for strings which start and end with a quote and contain the search term.
I am building an insert command to execute using jdbc. Part of it is to concatenate a user generated string...this all works until the user uses a string like this:
a'bcd
String userString="a'bcd";
String insertTableSQL = "INSERT INTO myTable "
+ "(insertColumn) "
+ "VALUES("
+"'"+userString+"'"
+")";
statement.executeUpdate(insertTableSQL);
You can do either of the below:
Use the PreparedStatement class. (Recommended)
String userString="a'bcd";
String myStatement = " INSERT INTO MYTABLE (INSERTCOLUMN) VALUES (?)";
PreparedStatement statement= con.prepareStatement (myStatement );
statement.setString(1,userString);
statement.executeUpdate();
Escape the single quotes.
In SQL, single quotes will be escaped by using double single quotes. ' --> ''
String userString="a'bcd";
String changedUserString = userString.replace("'","''");
//changedUserString = a''bcd
String insertTableSQL = "INSERT INTO myTable (insertColumn) VALUES("
+" '"+changedUserString +"' )";
You can use StringEscapeUtils from the Apache Commons Lang library.
Using this you can escape characters from html, xml, sql, etc. Look for method escapeXXX for your purpose. For reference: When i need to escape Html string?
note: escapeSql was removed in Apache Commons Lang 3 (see Migrating StringEscapeUtils.escapeSql from commons.lang which references https://commons.apache.org/proper/commons-lang/article3_0.html#StringEscapeUtils.escapeSql)
Eg:
String str = FileUtils.readFileToString(new File("input.txt"));
String results = StringEscapeUtils.escapeHtml(str);
System.out.println(results);
Input:
<sometext>
Here is some "Text" that I'd like to be "escaped" for HTML
& here is some Swedish: Tack. Vars?god.
</sometext>
Output:
<sometext>
Here is some "Text" that I'd like to be "escaped" for HTML
& here is some Swedish: Tack. Varsågod.
</sometext>
Here's another option:
Use a native Android method designed for exactly this purpose:
DatabaseUtils.sqlEscapeString(String)
Here is the documentation for it online:
sqlEscapeString() on Android Developers
The main advantage of using this method, in my opinion, is the self-documentation because of the clear method name.
String userString="a'bcd";
String insertTableSQL = "INSERT INTO myTable "
+ "(insertColumn) "
+ "VALUES("
+"'"+DatabaseUtils.sqlEscapeString(userString)+"'"
+")";
statement.executeUpdate(insertTableSQL);
I am using an sql query to add data data to an existing database table.
I want to add data under the columns 'Room_Resource' and 'Quantity'.
The system is designed to allow bookings and i am trying to add bookings made to a tblBookings table, the code below is taken from JButton clicked function.
The value I want to add to Room_Resource is a name taken from a selected table within the system. I declared a variable for this 'resourceChosenString'
The value I want to add to quantity is from the 'Quantity' variable i have declared in relation to a combo box.
Here are my declarations:
int selectedResourceRow = tblResources.getSelectedRow();
Object resourceChosen = tblResources.getValueAt(selectedResourceRow,1);
String resourceChosenString = resourceChosen.toString();
int Quantity = cmbQuantity.getSelectedIndex();
I then have a sql statement:
String sql = ("INSERT INTO tblBookings (Room_Resource,Quantity) VALUES (" + resourceChosenString + " ', ' " + Quantity + " ',) ");
And then the execute code:
try{
pst = conn.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(null, "Added");
} catch (Exception e){
JOptionPane.showMessageDialog(null, "Error Adding Booking");
}
Currently it gives me an error when I attempt to add the data to the table and wondered if anyone had any suggestions?
Also I considered that perhaps the problem could lie in the fact I have more than two columns in the external table and the table I am adding the data to so columns could be left blank. If this could be the problem, could anyone tell me how to get around it? Possibly if there is a null function I can use instead of values.
You probably want to tell us what database you're using and what error message you're getting. But just off the bat, it looks like your sql string is not formatted correctly. I don't know if you mistyped it in the question or if your code has a simple syntax error.
Just shooting from the hip with what you have, it looks like your sql statement should be:
String sql = "INSERT INTO tblBookings (Room_Resource,Quantity) VALUES ('" + resourceChosenString + "', " + Quantity + ")";
Notice that resourceChosenString should be wrapped in single quotes (you're missing the single quote on the left). Also, I don't think you're supposed to wrap a number in single quotes (I could be wrong since I don't know which database you're using).
Qwerky is right though; you should use a PreparedStatement.
The SQL you are generating is not valid and looks like this;
INSERT INTO tblBookings (Room_Resource,Quantity) VALUES (resource ', ' 1 ',)
^ ^
missing quote extraneous comma
You should tidy it up, or better still use a PreparedStatement.
String sql = "insert into tblBookings (Room_Resource,Quantity) values (?, ?)";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, resourceChosenString);
pst.setInt(2, quantity); //variable names are not capitalised by convention
pst.execute();
I wrote a simple SQL query in Oracle which inserts some values.
But I got SQLSyntaxErrorException stating a "missing expression" error.
This my query:
String addManager = "INSERT INTO property_manager(EIN,NAME,HOME_PHONENUMBER,MOBILE_PHONENUMBER,EMAIL,PROPERTY_CIN)" +
"VALUES (" + mein.getText() + "," + mname.getText() +","+ mHome_phonenumber.getText() +","+ MMobile_phonenumber.getText()+"," + memail.getText() + ","+mproperty_cin.getText()+")";
The best solution is using a java.sql.PreparedStatement.
It prevents SQL injection
Escapes invalid characters in your Strings (such as ') and the characters which will break your query
handles null and empty Strings
Uses Oracle's query parsing cache (for better performance)
Handles types such as Date and Blob much easier
Just google for java PreparedStatemnt and you see lots of samples.
You should put your values inside quotes.
String addManager = "INSERT INTO property_manager(EIN,NAME,HOME_PHONENUMBER,MOBILE_PHONENUMBER,EMAIL,PROPERTY_CIN)" +
"VALUES ('" + mein.getText() + "','" + mname.getText() +"','"+ mHome_phonenumber.getText() +"','"+ MMobile_phonenumber.getText()+"','" + memail.getText() + "','"+mproperty_cin.getText()+"')";
Or better yet, use parameters. Otherwise you risk sql injection attack.
Oracle keeps giving me an invalid identifier error when I clearly have identified the variable.
//get parameters from the request
String custID=request.getParameter("cust_ID");
String saleID=request.getParameter("sale_ID");
String firstName=request.getParameter("first_Name");
String mInitial=request.getParameter("mI");
String lastName=request.getParameter("last_Name");
String streetName=request.getParameter("street");
String city=request.getParameter("city");
String state=request.getParameter("state");
String zipCode=request.getParameter("zip_Code");
String DOB2=request.getParameter("DOB");
String agentID=request.getParameter("agent_ID");
String homePhone=request.getParameter("home_Phone");
String cellPhone=request.getParameter("cell_Phone");
String profession=request.getParameter("profession");
String employer=request.getParameter("employer");
String referrer=request.getParameter("referrer");
query =
"UPDATE customer"
+ " SET customer.cust_ID=custID, customer.sale_ID=saleID, customer.first_Name=firstName, customer.mI=mInitial, customer.last_Name=lastName, customer.street_Name=streetName, customer.city=city, customer.state=state, customer.zip_Code=zipCode,customer. DOB=DOB2, customer.agent_ID=agentID, customer.home_Phone=homePhone, customer.cell_Phone=cellPhone, customer.profession=profession, customer.employer=employer, customer.referrer=referrer"
+ " WHERE customer.cust_ID=custID " ;
preparedStatement = conn.prepareStatement(query);
preparedStatement.executeUpdate();
SQL TABLE
CREATE TABLE customer
(cust_ID NUMBER NOT NULL,
sale_ID NUMBER NOT NULL,
first_NameVARCHAR2(30) NOT NULL,
mI VARCHAR2(2) ,
last_Name VARCHAR2(50) NOT NULL,
street_Name VARCHAR2(50) ,
city VARCHAR2(30) NOT NULL,
state VARCHAR2(50) NOT NULL,
zip_Code VARCHAR2(5) NOT NULL,
DOB DATE ,
agent_ID NUMBER ,
home_Phone VARCHAR2(12) UNIQUE,
cell_Phone VARCHAR2(12) UNIQUE,
profession VARCHAR2(30) ,
employer VARCHAR2(30) ,
referrer VARCHAR2(30)
);
Your code is not doing what you think it is. Look at this:
query =
"UPDATE customer"
+ " SET customer.cust_ID=custID, customer.sale_ID=saleID, customer.first_Name=firstName, customer.mI=mInitial, customer.last_Name=lastName, customer.street_Name=streetName, customer.city=city, customer.state=state, customer.zip_Code=zipCode,customer. DOB=DOB2, customer.agent_ID=agentID, customer.home_Phone=homePhone, customer.cell_Phone=cellPhone, customer.profession=profession, customer.employer=employer, customer.referrer=referrer"
+ " WHERE customer.cust_ID=custID "
The content of query at this point is exactly what will be sent to the database. JSP will not magically fill in custID, saleID (etc...) for you before sending the query to the database. Because of this, Oracle has no sweet clue what custID is (it certainly isn't the name of some other column in the customer table). Hence, you receive the invalid identifier error.
I think you were trying to do this:
query =
"UPDATE customer"
+ " SET customer.cust_ID=" + custID + ", customer.sale_ID=" + saleID + ...
Like duffymo mentioned, this is asking for serious SQL-injection trouble (just think of the values that the client could submit in order to hijack your SQL via the custID field). The better way is to use parameters on a PreparedStatement:
query =
"UPDATE customer"
+ " SET customer.cust_ID=?, customer.sale_ID=? ...";
PreparedStatement statement = conn.prepareStatement(query);
statement.setString(1, custID);
statement.setString(2, saleID);
statement.executeUpdate();
I'd recommend not using scriplets in your JSPs. Learn JSTL as quickly as you can.
The answer seems pretty obvious: your parameters are all Strings, but the Oracle schema has some Data and Number types. You've got to convert to the correct type when you INSERT.
This code is begging for a SQL injection attack. You don't do any binding or validation before you INSERT. You couldn't possibly be less secure than this. I hope you don't intend to use this site for anything on the web.
A better approach would take the scriptlet code out of the JSP, use only JSTL to write it, and introduce a servlet and some other layers to help with binding, validation, security, etc.
I think in the sql query you have entered space in between customer,DOB.
customer. DOB=DOB2