I have one App working with the dataabase in which the organisation column having the records with the special characters(single quote). I am getting force close error while searching with the special character in the text field.
The code is below:
String name = idValues.getStringExtra("ORGNAME");
String sql ="select orgname from table1 where name like '%"+ name +"%' Order by org.name";
Please help me with the samplecode/links to search with the name containing special character.
Thanks in advance.
String name = idValues.getStringExtra("ORGNAME");
if (name.contains("'")) {
// Should replace all the charecters
name = name.replaceAll("'", "''");
}
String sql ="select orgname from table1 where name like '%"+ name +"%' Order by org.name";
Replace the single quote(') in the String as shown. Please try this.
Try Using PreparedStatement like this :
PreparedStatement pstmt = null;
String sql ="select orgname from table1 where name like ? Order by orgname";
pstmt.setString(1,"%"+name+"%");
ResultSet rs = pstmt.executeQuery();
No Error checks have been done .
Related
I want to replace table name in a sql query string. I only want to change table name. How can I do that in java with regex?
I do not want to use any dependencies.
For example,
Input:
select ... from table1 where/etc ....
expected output:
select ... from UPDATED_TABLE_NAME where/etc ....
If you mutate the query explicitly you open yourself to SQL injection. What you could do is use a PreparedStatement with a parameterized query to provide the table name safely.
try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM ?")) {
statement.setString(1, "my_table");
try (ResultSet results = statement.executeQuery()) {
}
}
If you're insistent on using regex you can just use the query above and replace ? with the table name. I would not do this in a production environment.
String query = "SELECT * FROM ?";
String queryWithTable = query.replaceAll("?", "my_table");
I was writing a prepared statement and for the table name I passed user obtained variable string.
So this works,
String m_table_variable = "blah"; // get from request object
PreparedStatement ps = conn.prepareStatement("select * from "+m_table_variable+"");
While this does not,
PreparedStatement ps = conn.prepareStatement("select * from '+m_table_variable+'")
What triviality am I missing here?
PreparedStatement ps = conn.prepareStatement("select * from " +m_table_variable)
try this
of course if the m_table_variable is a String with name of a table
Your problem is quite straight forward, the first example concatenates three Strings namely "select * from ", "blah" and "" together.
The second example uses one String which literally is "select * from '+m_table_variable+'" and the variable is not concatenated to the final String. Personally I wouldn't dynamically allow the table name to be injected into the SQL statement, read up on SQL injection.
Your first one will not even compile, you need to use \" to insert a quote into a string literal.
You need to escape " from String using \, otherwise it will not compile.
PreparedStatement ps
= conn.prepareStatement("select * from \"m_table_variable\"");
I have following String like that:String sql = "SELECT COL1, COL2, COL3 FROM SCHEMA.TABLE";
Now I need to get this value from String: SCHEMA.TABLE and this value is always changing. And also entire SQL is always changing.
How would I achieve this?
Don't know how to manipulate with different values?
This value is always after FROM and SQL may also have other values after FROM(ORDER BY, GROUP BY...)
SAMPLE SQL:
`SELECT ZGAR.ZGAR_ID, JARTI.ARTI_NAME, JZGAR.ZGAR_NAME, ZGAR.KAZG_ID, ZGAR.KZPO_ID, JZGAR.ZGAR_DESC FROM NETZGP.ZGANJEARTIKEL ZGAR LEFT JOIN NETZGP.J_ARTI JZGAR ON ZGAR.ZGAR_ID = JZGAR.ZGAR_ID LEFT JOIN NETZGP.J_ARTIKEL JARTI ON ZGAR.ARTI_ID = JARTI.ARTI_ID AND JZGAR.JEZI_ID = JARTI.JEZI_ID WHERE ZGAR.ARTI_ID = 1 AND JZGAR.JEZI_ID = 1 WITH UR`
The most succinct and reliable way is via regex:
String tableName = sql.replaceAll(".*FROM (\\S+).*", "$1");
This will also work when there's a WHERE clause after the table name.
Try with substring().
String result= queryString.substring(queryString.lastIndexOf(" ")+1);
gives the last part of the query.
If atleast FROM is there in every query
String[] result= s.split("FROM");
System.out.println(result[1]);
Use:String table= queryString.substring(queryString.lastIndexOf(" ")+1);
See String#substring().
If your sql query is changing frequently, you should use PreparedStatement instead of creating Statement many times.
Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement pst = con.prepareStatement("SELECT COL1, COL2, COL3 FROM ?");
String schemaTable = "<ANY_TEXT>";
p.setString(1, schemaTable);
ResultSet rs = p.executeQuery();
After that you can just change the schemaTable variable and again do p.setString(1, schemaTable); rs = p.executeQuery(); to get new results.
I m writing a small utility that captures and logs SQL statements, but will have to remove sensitive data from the Query text and replace with with some dummy text (i.e:XXXXX).
What is a good way to parse the SQL query in java and replace parameters value?
for example:
replace
SELECT NAME, ADDRESS, .... FROM USER WHERE SSN IN ('11111111111111', '22222222222222');
with
SELECT NAME, ADDRESS, .... FROM USER WHERE SSN IN (?, ?);
Using JSQLParser (V0.8.9) this is a solution for your problem:
String sql ="SELECT NAME, ADDRESS, COL1 FROM USER WHERE SSN IN ('11111111111111', '22222222222222');";
Select select = (Select) CCJSqlParserUtil.parse(sql);
//Start of value modification
StringBuilder buffer = new StringBuilder();
ExpressionDeParser expressionDeParser = new ExpressionDeParser() {
#Override
public void visit(StringValue stringValue) {
this.getBuffer().append("XXXX");
}
};
SelectDeParser deparser = new SelectDeParser(expressionDeParser,buffer );
expressionDeParser.setSelectVisitor(deparser);
expressionDeParser.setBuffer(buffer);
select.getSelectBody().accept(deparser);
//End of value modification
System.out.println(buffer.toString());
//Result is: SELECT NAME, ADDRESS, COL1 FROM USER WHERE SSN IN (XXXX, XXXX)
This replaces all found String values within your SQL. To replace other types of data e.g. Long values, override the corresponding visit method in ExpressionDeParser.
Don't use regexp in this case. It turns out quickly to be hard maintainable.
The correct answer depends on how much you want to replace. Something like:
[0-9]{3}-?[0-9]{2}-?[0-9]{4}
will replace social security numbers pretty well. I always take regex code to
regexpal.com
to tweak it and work out bugs.
If you need to replace tons of sensitive information though, and if there are a lot of cases, definitely start looking into using a parser to parse the SQL query string. (such as jsqlparser, as Anirudh recommended.)
String sqlDebit = select * from table where and billing_cycle_start_date between :startDate and :endDate
java:
sqlDebit= sqlDebit.replaceAll(":startDate ", ""+startDate).replaceAll(":endDate", ""+endDate);
With prepare statement you can replace "?" in your query string with your value. Use number to specify which "?" you are referring too. They go by order from right to left.
For example: "SELECT LastName, FirstName FROM Person.Contact WHERE LastName = ? and FirstName = ?"
pstmt.setString(1, "LastNameValue");
pstmt.setString(2, "FirstNameValue");
see full example below:
public static void executeStatement(Connection con) {
try(PreparedStatement pstmt = con.prepareStatement("SELECT LastName, FirstName FROM Person.Contact WHERE LastName = ?");) {
pstmt.setString(1, "Smith");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
}
}
// Handle any errors that may have occurred.
catch (SQLException e) {
e.printStackTrace();
}
}
I have a table where there is a column with this name : bureau d'étude
When I do a select :
String sql = "select bureau d'étude from table";
the server show me a syntax error. How to hide or replace this apostrophe ?
You should really use a PreparedStatement to avoid these problems and thus SQL injections:
PreparedStatement statementSelect;
String sql = "select ? from ?";
try
{
statementSelect = myConnection.prepareStatement(sql);
statementSelect.setString(1,"bureau d'étude");
statementSelect.setString(2,"table");
statementSelect.executeQuery();
}
catch (SQLException e )
{
//handle this
}
String sql = "select `bureau d''étude` from table";
Since there is a space in the column name make sure you encapsulate it with `.
Furthermore, you can escape a single quote with another single quote.
You can Try following:
String sql = "select [bureau d''étude] from table";