How to escape " ' " in sql - java

Hi I am searching for a name combination in database. I am passing the combination as follows
"firstName='" + firstName + "'", "middleName='" + middleName + "'", "lastName='" + lastName + "'"
This works fine. But the problem comes where there are some " ' " in names how can i rectify it? eg: Johns' or Jerry's etc causes exception

use preparedStatement it is easy for you
ps.executeUpdate("INSERT INTO tb_name values(?,?) WHERE id=?");
ps.setString(1,firstName);
ps.setString(2,middleName);
ps.setInt(3,id);
ps.execute();

At least for MySQL, you have to put another ' before:
INSERT INTO table (column) VALUES ('this isn''t it');

If you're using Hibernate, you should use like this:
Query query = session.createQuery("from Something s where s.firstName = :firstName and s.middleName = :middleName and s.lastName = :lastName");
query.setString("firstName", firstName);
query.setString("middleName", middleName);
query.setString("lastName", lastName);
List<?> list = query.list();
Hope this can help you!
You can see more at here and here

String firstName="X";
String middleName="Y";
String lastName="Z";
"firstName='" + firstName + "',middleName='" + middleName + "',lastName='" + lastName + "'";
You can use this to get output as
firstName='X',middleName='Y',lastName='Z'

You can ignore sinqle quotation characters (') in SQL by escaping them with a backslash \'.

Try this:
firstName = firstName.replace("'" , "''");
Use PreparedStatement instead , you would be better with that.

I guess the following also works (at least for MySQL):
SELECT login FROM usertable WHERE lastname="O'Neil";

Related

This use of PreparedStatement; can be vulnerable to SQL injection (with JDBC)

My sql query looks like this:
String sqlAlloc = " select %1$s from %2$s "
+ "where plot_fk in (%3$s) and plot_fk between ? and ? "
+ "and f001=? "
+ "and repdate=TO_CHAR(TO_DATE(?,'YYYYMMDD'), 'DD-Mon-YY') "
+ "and reportname = ? and change_status in (0,2,6,8,9)";
if (!cond.isEmpty()) {
sqlAlloc += " and C007=?";
}
if (tableName.getKey().equals(ALLOC_PENSIONFUNDS)) {
sqlAlloc += " group by REPDATE, F001, C007, REPORTNAME, COLNAME, ROWNAME";
}
List<String> values = Arrays.asList(tableName.getValue().split(","));
String sqlAllocFormatted = String.format(sqlAlloc,
values.stream().collect(Collectors.joining(",")),
jdbcUsernameMaster + "." + key,
plotFkMasterPublicList.stream()
.collect(Collectors.joining(",")));
try (final Connection conn = ds.getConnection();
final PreparedStatement stmtAlloc =
conn.prepareStatement(sqlAllocFormatted);) {
...
When I scan my code with sonarqube I get the following msg:
This use of PreparedStatement; can be vulnerable to SQL injection (with JDBC)
I don't really understand what is wrong with the sql query and how to fix this?
The vulnerability lies in the fact that you are using String.format to inject things into your query string. If the values of values/tableName and jdbcUsernameMaster, key and plotFkMasterPublicList come from an untrusted source, then this could be a potential source of SQL injection.
To fix this, you either need to not use String.format, but static query strings, or you need to ensure that your values are not from an untrusted source (e.g. user input, external services, etc), and then consciously suppress the warning as a false-positive.
The SQL Injection is really hard to exploit in this particulare case, but if you know the query executed and plotFKMAsterPublicList can be manipultated you can create a "bad query".
What follows is an example based on your original code:
String sqlAlloc = " select %1$s from %2$s "
+ "where plot_fk in (%3$s) and plot_fk between ? and ? "
+ "and f001=? "
+ "and repdate=TO_CHAR(TO_DATE(?,'YYYYMMDD'), 'DD-Mon-YY') "
+ "and reportname = ? and change_status in (0,2,6,8,9)";
List<String> values = Arrays.asList("col1,col2".split(","));
List plotFkMasterPublicList= new ArrayList<>();
plotFkMasterPublicList.add("plot1");
plotFkMasterPublicList.add("plot2");
plotFkMasterPublicList.add("plot3) union all select col1,col2 from user.table union all select col1,col2 from user.table where (1=1 ");
String sqlAllocFormatted = String.format(sqlAlloc,
values.stream().collect(Collectors.joining(",")),
"user" + "." + "table",
plotFkMasterPublicList.stream()
.collect(Collectors.joining(",")));
System.out.println(sqlAllocFormatted);
Thanks to #MarkRotteveel suggestion you can query whatever you want, see these example:
String sqlAlloc = " select %1$s from %2$s "
+ "where plot_fk in (%3$s) and plot_fk between ? and ? "
+ "and f001=? "
+ "and repdate=TO_CHAR(TO_DATE(?,'YYYYMMDD'), 'DD-Mon-YY') "
+ "and reportname = ? and change_status in (0,2,6,8,9)";
List<String> values = Arrays.asList("* from any_table -- col1,col2".split(","));
List plotFkMasterPublicList= new ArrayList<>();
plotFkMasterPublicList.add("plot1");
plotFkMasterPublicList.add("plot2");
String sqlAllocFormatted = String.format(sqlAlloc,
values.stream().collect(Collectors.joining(",")),
"user" + "." + "table",
plotFkMasterPublicList.stream()
.collect(Collectors.joining(",")));
System.out.println(sqlAllocFormatted);

How to insert DATE using jsp

I have a feedback page on my site that contains name, email and comments. Here is my code on JSP and I'm using Apache Tomcat 7.0 and Oracle DB
String query = "Insert into t_comments(name, email, comments) values('"
+ realname
+ "','"
+ email
+ "','"
+ comments+"')";
This works great. But I decided to add DATEC column (data type DATE) to my table t_comments. So my query should look like
String query = "Insert into t_comments(name, email, comments,datec) values('"
+ realname
+ "','"
+ email
+ "','"
+ comments
+ "',"
+ "TO_DATE('"
+ new java.util.Date()
+ "', 'dd/mm/yyyy hh24:mi:ss'))";
And this doesn't work.
ORA-01858: a non-numeric character was found where a numeric was expected
Maybe I insert wrongly type DATE into my table. Also I have another problem. The name and comments are in Cyrillic. And when they inserted in table, they are displayed incorrect with different encoding. I have this lines in my JSP page
<%# page language='java' contentType='text/html; charset=UTF-8' pageEncoding='UTF-8'%>
So help me please solve my two problems
insert DATE to my table
insert Cyrillic words correct to my table
Thanks
Let oracle do it for you instead.
String query = "Insert into t_comments(name, email, comments,datec) values('"
+ realname
+ "','"
+ email
+ "','"
+ comments
+ "', CURRENT_TIMESTAMP)";
See this link for more info.
You should debug your code and check if a Date object toString() matches the pattern expected by Oracle.
Potentially, if you don't want to go in Arvind's way (which I think it's a good idea actually), you can format your Date using SimpleDateFormat.
You should also consider using a PreparedStatement instead of building the statement using String concatenation.
I thank all for your answers. I'm using CURRENT_TIMESTAMP to insert DATE to my table from #Arvind Sridharan and for cyrillic characters I added the following lines in my jsp
request.setCharacterEncoding("UTF-8");
realname = new String(realname.getBytes("ISO-8859-1"),"UTF8");
comments = new String(comments.getBytes("ISO-8859-1"),"UTF8");

fetch value from SQL query list

So i just wrote down this SQL query and i am trying to capture the value of rest_id in query.list(). However, this is giving the value as [1] . I want just 1 without the braces. How do i do it? Please check the code below for reference:
String sql1 = "select rest_id from rest_details where rest_name = '" + nameclicked + "' and rest_location = '" +locclicked + "'" ;
SQLQuery query1 = session.createSQLQuery(sql1);
System.out.println("sql1 " + query1.list());
Use below code to get the element inside list:
System.out.println("sql1 " + query1.list().get(0));
This always returns only the first element from the list.
Replace
System.out.println("sql1 " + query1.list());
By :
for(String id : query1.list() ) System.out.println("sql1 " + id);

Escaping a single quote when using JdbcTemplate

We're using JdbcTemplate to modify our underlying Oracle database. We're doing this by way of the update(String sql) method.
The code looks somehow like the following:
String name = "My name's yellow";
String sql = "update FIELD set NAME = '" + name "' where ID = 10
jdbcTemplate.update(sql);
This causes the error:
java.sql.SQLException: ORA-00933: SQL command not properly ended
The problem is the unescaped ' in the name variable.
What's the most convenient and correct way to escape this character?
Use PreparedStatement. That way you nominate a placeholder and the JDBC driver will perform this correctly by sending the database the statement, plus the parameters as arguments.
String updateStatement =
"update " + dbName + ".COFFEES " +
"set TOTAL = TOTAL + ? " +
"where COF_NAME = ?";
PreparedStatement updateTotal = con.prepareStatement(updateStatement);
updateTotal.setInt(1, e.getValue().intValue());
updateTotal.setString(2, e.getKey());
The question marks in the above represent the placeholders.
Because these values get passed as parameters, you don't have problems with quoting, and it protects you against SQL injection too.
Try for name :
if ( name.contains("'") ){
name.replaceAll("'", "''");
}

deleting a record which selected by user?

I am coding
String Name = txtName.getText();
String Surname = txtSurname.getText();
st.executeUpdate("DELETE from list WHERE Name=#Name and Surname=#Surname");
but it doesn't delete the records. Any problem with the syntax? Please help.
You need to replace #name and #surname with the actual values.
and add ' around your values:
DELETE from list WHERE Name='#Name' and Surname='#Surname'
String Name = txtName.getText().Trim();
String Surname = txtSurname.getText().Trim();
String query = "DELETE from list WHERE Name='" + Name + "' and Surname='" + Surname + "'";
st.executeUpdate(query);
try:
st.executeNonQuery("DELETE from list WHERE Name=?e and Surname=?");
and pass the name and surname as parameters.
Use this
If the table list exists .
This will work .
String Name = txtName.getText();
String Surname = txtSurname.getText();
st.executeUpdate("DELETE from list WHERE Name='"+Name"' and Surname='"+Surname"'");
I fixed it like that:
st.executeUpdate("DELETE from list WHERE Name='"+txtName.getText()+"'" + "and Surname='" + txtSurname.getText()+"'");
Thank you all

Categories

Resources