How to replace table name in sql query with regex in Java? - java

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");

Related

how to add sql parametrized queries through jdbc java

I have to develop a parameterized sql staement something like this below
select * from tablename where cid = cid
so below is the rest service which is calling a method so the user is passing the input parameters like tablename and cid and basis on that it
will go to database and to that particular table and will retrieve the coulmn values so below is the code now in the below code please advise
how can i change the sql statement to be parametrized so that it will retrieve the value from the table onm the basis of cid input by the user
public String retriveData(#QueryParam("tablename") String tablename,#QueryParam("cid") String cid ) throws SQLException
{
Connection con=null;
PreparedStatement ps=null;
String statement="";
String retString="";
try {
//Class.forName("com.mysql.jdbc.Driver");
//put sql jdbc jar in tomcat lib
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con=DriverManager.getConnection("jdbc:sqlserver://xxx:1111; databaseName=aaa", "rr","vvv");
con.setAutoCommit(false);
System.out.println("FROM TABLE NAME : "+tablename);// ***** need to be parametrized query basis on the cid ******
statement="SELECT * FROM "+tablename+";";// ***** need to be parametrized query basis on the cid ********
System.out.println("STATEMENT : "+statement);
ps=con.prepareStatement(statement);
// Turn use of the cursor on.
//ps.setFetchSize(50);
ps.setMaxRows(10);
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
String name=rsmd.getColumnName(5);
while(rs.next())
{
retString=retString+name+" : "+rs.getString(name)+"<br>";
System.out.println(retString);
}
You can't. You need to contruct the sql with string concatenation/placeholder with String.format. prepared statement is for the column values not for table name.
Sources: How to use a tablename variable for a java prepared statement insert
How to pass table name to a Prepared Statement in a SELECT COUNT query?
I'm not sure about why you wanted to parametrized the table name.
But parametrized for cid is OK by using the prepared statement like below.
statement="SELECT * FROM " + tablename + " where cid = ?";
preparedStatement.setInt(1, cid);
If you want to retrieve values from specific table by filtering with cid, that will be the answer I guess.

Unknown column '$a' in 'where clause'

i want to fetch data from database by using a variable string.it shows error
"Unknown column '$a' in 'where clause'"
String a=request.getParameter("from");
ResultSet resultset= statement.executeQuery("select * from flight where f = $a") ;
If you want to use the value of the a variable where you have $a, you need to use a prepared statement and fill it in:
String a = request.getParameter("from");
PreparedStatement ps = connection.prepareStatement( // Create a prepared statement
"select * from flight where f = ?" // Using ? for where the
); // parameter goes
ps.setString(1, a); // Fill in the value (they
// start a 1, oddly)
ResultSet resultset = ps.executeQuery(); // Execute the query
Note that even though it's a string, you don't put quotes around the ?. The PreparedStatement handles that for you at the DB driver level, in a way that's safe from SQL injection.

How can handle reserved character in SQL query

I want to read data from a table but I got a error because the value I want to compare may contain a word like this: abcd l'jdmd
I try it like this:
String s = "select ref(ad) from adresse_tab ad where ad.ort='"+rs.getString(11)+"' and ad.plz='"+rs.getString(13)+"' and ad.land='"+rs.getString(14)+"'";
PreparedStatement stmt5 = nsdCon.prepareStatement(s);
ResultSet rs5 = stmt5.executeQuery();
The query could look like this:
select ref(ad)
from adresse_tab ad
where ad.ort='Frankfurt am Main'
and ad.plz='65301'
and ad.land='Deutschland'
and ad.strasse='almundo l'tare '
So the problem in this query is this comparison:
ad.strasse='almundo l'tare '
How can I handle reserved character in SQL query?
Please avoid creating a SQL query with supplied parameters using string concatenation. Instead you can continue using PreparedStatement, but use placeholders for the actual param values, and use the statement's set<X>() methods for setting params. Here's official Oracle docs on this.
You must supply values in place of the question mark placeholders (if
there are any) before you can execute a PreparedStatement object. Do
this by calling one of the setter methods defined in the
PreparedStatement class. The following statements supply the two
question mark placeholders in the PreparedStatement named updateSales:
updateSales.setInt(1, e.getValue().intValue());
updateSales.setString(2, e.getKey()); The first argument for each of
these setter methods specifies the question mark placeholder. In this
example, setInt specifies the first placeholder and setString
specifies the second placeholder.
For your case:
String s = "select ref(ad) from adresse_tab ad where ad.ort=? and ad.plz=? and ad.land=?";
PreparedStatement stmt5 = nsdCon.prepareStatement(s);
stmt5.setString(1, rs.getString(11));
... and so on
Use a prepared statement (and for added clarity of named bind variables you can use an OraclePreparedStatement):
String s = "select ref(ad) from adresse_tab ad where ad.ort=:ort and ad.plz=:plz and ad.land=:land";
PreparedStatement st5 = nsdCon.prepareStatement(s);
OraclePreparedStatement ost5 = (OraclePreparedStatement) st5;
ost5.setStringAtName("ort",rs.getString(11))
ost5.setStringAtName("plz",rs.getString(13))
ost5.setStringAtName("land",rs.getString(14))
ResultSet rs5 = st5.executeQuery();
You should not add your query parameters directly to the query string. Use a Prepared Statement instead and pass the query parameters there. See also Does the preparedStatement avoid SQL injection?
The whole point of prepared statements is to use parameters within your query so values can be automatically escaped:
String s = "select ref(ad) from adresse_tab ad where ad.ort=? and ad.plz=? and ad.land=?";
PreparedStatement stmt5 = nsdCon.prepareStatement(s);
stmt5.setString(1, rs.getString(11));
stmt5.setString(2, rs.getString(13));
stmt5.setString(3, rs.getString(14));
ResultSet rs5 = stmt5.executeQuery();
ad.strasse='almundo l'''tare '

Using PrepareStatement to get data with configurable table name

I'm trying to get some data from Oracle 11.2 using java and jdbc driver.
My goal is to get data from database using CallableStatement, but with no luck - I'm not able to put table name as parameter. I would like to have configurable table name in query. However, it would be good to keep it sanitized.
Here is an example..
public void getData() throws SQLException {
Connection conn = Config.getSQLConnection();
String query = "SELECT * FROM ?";
PreparedStatement st = conn.prepareStatement(query);
st.setString(1, Config.DATATABLE_NAME);
ResultSet rs = st.executeQuery();
if (rs.next()) {
System.out.println("SUCCESS");
System.out.println("ID:" + rs.getString("ID"));
} else {
System.out.println("FAILURE");
}
}
Is this the way it should work? Or am I missing something, or misused it?
A CallableStatement is used to make call to stored procedures.
From javadoc:
The interface used to execute SQL stored procedures
Use a PreparedStament instead for a normal select.
As an additional note don't pass the name of the table as parameter.
Create the query using concatenation.
Instead of
String query = "SELECT * FROM ?";
use
String query = "SELECT * FROM " + Config.DATATABLE_NAME;
You should use PreparedStatement instead of CallableStatement.
CallableStatement is an interface which is used to call stored procedures.

select a column name with apostroph from mysql database

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";

Categories

Resources