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.
Related
The query inside MySQL is working:
DELETE FROM f9.yoo
WHERE account_tags = '#8GGGJPUR9'
I can delete data inside MySQL, but the problem is whenever I try to remove the account_tags from my Java application, it throws an error:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELETE FROM f9.yoo
WHERE account_tags = '#8GGGJPUR9'' at line 2
Here's my Java SQL query:
Statement statement = dbConnection.createStatement();
String sql = "SELECT * FROM "+databaseName+"."+tableName+";\n" +
"DELETE FROM "+databaseName+"."+tableName+"\n" +
"WHERE account_tags = '"+AccountTag+"';";
statement.executeQuery(sql);
The error isn't giving me much to work with, so I really have no idea what is wrong with the program.
Did you add the allowMultiQueries=true
If not then you can add that while you sending the connecting request to your database. So you need to append the allowMultiQueries=true in your to database URL.
Like this:
String dbUrl = "jdbc:mysql:///test?allowMultiQueries=true";
String sql = "DELETE FROM "+databaseName+"."+tableName+"\n" +
"WHERE account_tags = ?";
try (PreparedStatement statement = dbConnection.prepareStatement(sq)) {
statement.setString(1, AccountTag);
int updateCount = statement.executeUpdate();
System.out.printf("%s: %d records deleted.%n", tableName, updateCount);
}
The only thing used is the DELETE, for which one should use executeUpdate.
One definitely should use a PreparedStatement as many code checkers will give alarms otherwise. It escapes things like ', handles types of the arguments, and possible conversions, and especially is a security feature against SQL injection.
The System.out usage is bad style, better would be using a logger.
try-with-resources automatically closes the PreparedStatement even with a raised exception or break/return.
When doing both database operations, it seems better to use two (prepared) statements, as the first returns a ResultSet.
So:
String sql = SELECT * FROM "+databaseName+"."+tableName + "\n" +
"WHERE account_tags = ?";
try (PreparedStatement statement = dbConnection.prepareStatement(sq)) {
statement.setString(1, AccountTag);
try (ResultSet rs = statement.executeQuery()) {
...
}
}
Better to separate statements with an If condition :
String sql1="SELECT * FROM "+databaseName+"."+tableName;
String sql2="DELETE FROM "+databaseName+"."+tableName+" "+
"WHERE account_tags = '"+AccountTag+"';
statement.executeQuery(sql1);
statement.executeUpdate(sql2);
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'm working on a simple application that pulls data from a local database. The below code works fine when I use a string for the SQL query, but I can not get it to work with PreparedStatement. I have reviewed similar problems posted here but most of those were caused by doing this, preparedStmt.executeQuery(query); instead of this preparedStmt.executeQuery(); Here is the code,
private final String POSTTITLE= "posttitle"; // DB Column name
private final String POSTCONTENT= "content"; // DB Column name
public String getDbContent(){
try{
String query ="select values(?, ?) from blog";
PreparedStatement preparedStmt = this.connect.prepareStatement(query);
preparedStmt.setString (1,POSTTITLE);
preparedStmt.setString (2,POSTCONTENT);
ResultSet rs = preparedStmt.executeQuery();
rs.next();
return(rs.getString(this.POSTCONTENT)); //Will replace with loop to get all content
} catch(Exception e) {
System.err.println("Error Reading database!");
System.err.println(e);
return("Error: "+e);
}
}
This is the error I get:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''posttitle', 'content') from blog' at line 1
Parameters in prepared statements are for values - you're trying to use them to select fields. They just don't work that way.
In this very specific instance, you'll need to make the SQL dynamic. However, you'll want to make sure that whatever code you have to allow your columns to be specified is tightly constrained to avoid SQL injection attacks. (For example, you could have an enum with the columns in, or a whitelist of allowed values.)
Try concatenating select query:
String query ="select "+POSTTITLE+","+POSTCONTENT+" from blog";
Remember that prepared statements are for values, not query parameters, for them we use simply concatenations.
Try this:
String query ="select POSTTITLE, POSTCONTENT from blog";
PreparedStatement preparedStmt = this.connect.prepareStatement(query);
ResultSet rs = preparedStmt.executeQuery();
rs.next();
There is no need to use field names as parameter.
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.
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.