I'm familiar with using java prepared statements to insert/update on a table. In oracle you can add a comment on a table, how would I use a preparedstatement to do that?
This was my initial attempt with no luck;
PreparedStatement stmt = con.prepareStatement("comment on table my_table is q'[?]'");
stmt.setString(1, description);
stmt.executeUpdate();
You can use system Oracle table and set comment there with PreparedStatement, like this:
PreparedStatement stmt = con.prepareStatement(
"UPDATE user_tab_comments SET comments = ? WHERE table_name = 'my_table'");
Or try to use simple statement:
String commentOnTableSQL = String.format("COMMENT ON TABLE my_table is '%s'", comment);
Statement statement = dbConnection.createStatement();
statement.execute(commentOnTableSQL);
Related
A security scan made by AppScan source flags that the input has to be validated (Validation.Required) on the line uprs.updateString in the code below:
PreparedStatement statement =
conn.prepareStatement (query, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
...
ResultSet uprs = statement.executeQuery ();
...
// Update DB ColumnA with input coming from client
uprs.updateString ('ColumnA', unvalidatedUserInput);
...
// Updates the underlying database
uprs.updateRow();
I assume that the intention behind this is to avoid SQL injection attacks, but I'm not sure whether that is possible in that scenario.
Questions: Are SQL Injection attacks possible through these JDBC methods? How does JDBC implements this under the scenes? Would this be another false positive reported by AppScan?
I'm not sure about bluemix-app-scan, but I'm providing my explanation here. (This is my assumption based on the below tests and code pasted)
I ran a test code to check this (in H2 DB)
value of testName String : (select 'sqlInjection' from dual)
Using createStatement (Not-Safe):
String query = "update TEST_TABLE set TEST_CHAR = " + testName + " where ID = 1";
Statement statement = connection.createStatement();
statement.executeUpdate(query);
Output: TEST_CHAR in DB was sqlInjection.
Using ResultSet of createStatement (Safe in H2 DB):
String query = "select * from TEST_TABLE where ID = 1";
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet executeQuery = statement.executeQuery(query);
executeQuery.next();
executeQuery.updateString("TEST_CHAR", testName);
executeQuery.updateRow();
Output: Surprisingly TEST_CHAR in DB was (select 'sqlInjection' from dual).
Using PreparedStatement (Safe):
String query = "update TEST_TABLE set TEST_CHAR = ? where ID = 1";
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, testName);
statement.executeUpdate();
Output: Expected - TEST_CHAR in DB was (select 'sqlInjection' from dual).
Using ResultSet of prepareStatement (Safe in H2 DB):
String query = "select * from TEST_TABLE where ID = 1";
PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = statement.executeQuery();
uprs.next();
uprs.updateString("TEST_CHAR", testName);
uprs.updateRow();
Output: Expected - TEST_CHAR in DB was (select 'sqlInjection' from dual).
Back to Questions:
Are SQL Injection attacks possible through these JDBC methods?
Maybe. It depends on the database driver that you're using.
How? :
The reason SQL Injection failed in my result set update was because H2 database internally uses PreparedStatement to update the row when ResultSet.updateRow() is invoked.
public void updateRow(Value[] current, Value[] updateRow) throws SQLException {
StatementBuilder buff = new StatementBuilder("UPDATE ");
...
buff.append(" SET ");
appendColumnList(buff, true);
...
appendKeyCondition(buff);
PreparedStatement prep = conn.prepareStatement(buff.toString());
...
for (int i = 0; i < columnCount; i++) {
...
v.set(prep, j++);
}
setKey(prep, j, current);
int count = prep.executeUpdate();
...
}
I'm not sure if all DB drivers in java implemented updateRow() method using preparedStatement or not. However it's clear that this is left to the driver and if bluemix is suggesting you to add a validation here, I suggest you follow that :)
How does JDBC implements this under the scenes?
Well, as shown above this is driver specific. However there is a good explanation on how PreparedStatement handles it over here.
Would this be another false positive reported by AppScan?
I don't think this is false positive (but in cases like H2 DB it is) but you'll never know if all database drivers implemented this securely.
Edit -
Even PostgreSQL and MySQL use PreparedStatement to handle this.
public synchronized void updateRow() throws SQLException
{
...
updateStatement = ((java.sql.Connection) connection).prepareStatement(updateSQL.toString());
...
updateStatement.executeUpdate();
...
}
This sql query is not updating the database, instead returning error. Any suggestions?
PreparedStatement ps10 = con.prepareStatement("UPDATE payroll_system.payslip SET hours_worked = (SELECT SUM(Hours) FROM payroll_system.monthly_timesheet WHERE employeeID=?) WHERE employeeID=?");
ps10.setString(1, employee_id);
ps10.setString(2, employee_id);
ps10.executeUpdate();
monthly_timesheet table:
payslip table:
Insert don't have where clause
"INSERT INTO payroll_system.payslip(expense_claims)
WHERE employeeID=?
SELECT SUM(expense) FROM payroll_system.expense_master"
eventually you are looking for update?
or use
"INSERT INTO payroll_system.payslip(expense_claims)
SELECT SUM(expense) FROM payroll_system.expense_mast"
for update
PreparedStatement ps9 = con.prepareStatement("UPDATE payroll_system.payslip
SET expense_claims = (SELECT SUM(Expense)
FROM payroll_system.expense_master
WHERE employeeID=?) WHERE employeeID=?");
ps9.setString(1, employee_id);
ps9.setString(2, employee_id);
ps9.executeUpdate();
Is there a way to retrieve the auto generated key from a DB query when using a java query with prepared statements.
For example, I know AutoGeneratedKeys can work as follows.
stmt = conn.createStatement();
stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
if(returnLastInsertId) {
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
However. What if I want to do an insert with a prepared Statement.
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql);
//this is an error
stmt.executeUpdate(Statement.RETURN_GENERATED_KEYS);
if(returnLastInsertId) {
//this is an error since the above is an error
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
Is there a way to do this that I don't know about. It seems from the javadoc that PreparedStatements can't return the Auto Generated ID.
Yes. See here. Section 7.1.9. Change your code to:
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.executeUpdate();
if(returnLastInsertId) {
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
There's a couple of ways, and it seems different jdbc drivers handles things a bit different, or not at all in some cases(some will only give you autogenerated primary keys, not other columns) but the basic forms are
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
Or use this form:
String autogenColumns[] = {"column1","column2"};
stmt = conn.prepareStatement(sql, autogenColumns)
Yes, There is a way. I just found this hiding in the java doc.
They way is to pass the AutoGeneratedKeys id as follows
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
I'm one of those that surfed through a few threads looking for solution of this issue ... and finally get it to work. FOR THOSE USING jdbc:oracle:thin: with ojdbc6.jar PLEASE TAKE NOTE:
You can use either methods:
(Method 1)
Try{
String yourSQL="insert into Table1(Id,Col2,Col3) values(SEQ.nextval,?,?)";
myPrepStatement = <Connection>.prepareStatement(yourSQL, Statement.RETURN_GENERATED_KEYS);
myPrepStatement.setInt(1, 123);
myPrepStatement.setInt(2, 123);
myPrepStatement.executeUpdate();
ResultSet rs = getGeneratedKeys;
if(rs.next()) {
java.sql.RowId rid=rs.getRowId(1);
//what you get is only a RowId ref, try make use of it anyway U could think of
System.out.println(rid);
}
} catch (SQLException e) {
//
}
(Method 2)
Try{
String yourSQL="insert into Table1(Id,Col2,Col3) values(SEQ.nextval,?,?)";
//IMPORTANT: here's where other threads don tell U, you need to list ALL cols
//mentioned in your query in the array
myPrepStatement = <Connection>.prepareStatement(yourSQL, new String[]{"Id","Col2","Col3"});
myPrepStatement.setInt(1, 123);
myPrepStatement.setInt(2, 123);
myPrepStatement.executeUpdate();
ResultSet rs = getGeneratedKeys;
if(rs.next()) {
//In this exp, the autoKey val is in 1st col
int id=rs.getLong(1);
//now this's a real value of col Id
System.out.println(id);
}
} catch (SQLException e) {
//
}
Basically, try not used Method1 if you just want the value of SEQ.Nextval, b'cse it just return the RowID ref that you may cracked your head finding way to make use of it, which also don fit all data type you tried casting it to! This may works fine (return actual val) in MySQL, DB2 but not in Oracle.
AND, turn off your SQL Developer, Toad or any client which use the same login session to do INSERT when you're debugging. It MAY not affect you every time (debugging call) ... until you find your apps freeze without exception for some time. Yes ... halt without exception!
Connection connection=null;
int generatedkey=0;
PreparedStatement pstmt=connection.prepareStatement("Your insert query");
ResultSet rs=pstmt.getGeneratedKeys();
if (rs.next()) {
generatedkey=rs.getInt(1);
System.out.println("Auto Generated Primary Key " + generatedkey);
}
String req="INSERT INTO NOTIFICATIONS VALUES(6,1,sysdate,'toz',02542,'bporp')(SELECT valide from mouvement where valide=?)";
I want to make a request with Conditions but I get the error:
SQL command not properly ended
You have an invalid SQL query. Here's your current SQL statement:
INSERT INTO NOTIFICATIONS VALUES(6,1,sysdate,'toz',02542,'bporp')(SELECT valide from mouvement where valide=?)
If we split this into several lines for better understanding, you will have this:
INSERT INTO NOTIFICATIONS
VALUES(6,1,sysdate,'toz',02542,'bporp')
(SELECT valide from mouvement where valide=?)
Which is not a valid statement, not even for any SQL tool. That's because you have 2 statements without separating them: an INSERT and then a SELECT, and you're not executing an INSERT INTO <TABLE1> SELECT ... FROM <TABLE2>.
You should execute a single SQL statement per Statement or PreparedStatement. This, in Java, should be done like this:
String sql1 = "INSERT INTO NOTIFICATIONS"
+ " VALUES(6,1,sysdate,'toz',02542,'bporp')";
String sql2 = "SELECT valide from mouvement where valide=?";
Statement stmt = con.createStatement();
stmt.executeUpdate(sql1);
PreparedStatement pstmt = con.prepareStatement(sql2);
pstmt.setString(1, <parameter_value>);
ResultSet rs = pstmt.executeQuery();
i have the below code, where I'm inserting records to a table. When I try to get resultset, it returns null. How to get the latest added row into a resultset?
String sql1 = "INSERT INTO [xxxx].[dbo].[xxxxxx](WORKFLOW_SEQ_NBR," +
" WORKFLOW_LOG_TYPE_CODE, WORKFLOW_STATUS_CODE, DISP_CODE, DISP_USER, DISP_COMMENT, DISP_TITLE, DISP_TS)" +
"VALUES(?,?,?,?,?,?,?,?)";
PreparedStatement pst = connect.prepareStatement(sql1);
pst.setString(1, ...);
pst.setString(2, ...);
...
...
...
pst.executeUpdate();
ResultSet rstest = pst.executeQuery();
// ResultSet rstest = pst.getResultSet();
EDIT: Resolved
added following method to go to the last added row
st.execute("Select * from [xxxx].[dbo].[xxxxxxxxx]");
ResultSet rstest = st.getResultSet();
rstest.afterLast();
GETLASTINSERTED:
while(rstest.previous()){
System.out.println(rstest.getObject(1));
break GETLASTINSERTED;//to read only the last row
}
When using a SQL statement such as INSERT, UPDATE or DELETE with a PreparedStatement, you must use executeUpdate, which will return the number of affeted rows. In this case there is simply no ResultSet produced by the sql operation and thus calling executeQuery will throw a SQLException.
If you actually need a ResultSet you must make another statement with a SELECT SQL operation.
See the javadoc for PreparedStatement#executeQuery and PreparedStatement#executeUpdate
Seems like this is an older question, but i'm looking for a similar solution, so maybe people will still need this.
If you're doing an insert statement, you can use the :
Connection.PreparedStatement(String, String[]) constructor, and assign those to a ResultSet with ps.getGeneratedKeys().
It would look something like this:
public void sqlQuery() {
PreparedStatement ps = null;
ResultSet rs = null;
Connection conn; //Assume this is a properly defined Connection
String sql = "insert whatever into whatever";
ps = conn.prepareStatement(sql, new String[]{"example"});
//do anything else you need to do with the preparedStatement
ps.execute;
rs = ps.getGeneratedKeys();
while(rs.next()){
//do whatever is needed with the ResultSet
}
ps.close();
rs.close();
}
Connection#prepareStatement() - Creates a PreparedStatement object for sending parameterized SQL statements to the database.
which means connect.prepareStatement(sql1); created the PreparedStatement object using your insert query.
and when you did pst.executeUpdate(); it will return the row count for SQL Data Manipulation Language (DML) statements or 0 for SQL statements that return nothing
Now if you again want to fetch the data inserted you need to create a new PreparedStatement object with Select query.
PreparedStatement pstmt = connect.prepareStatement("SELECT * FROM tableName");
then this shall give you the ResultSet object that contains the data produced by the query
ResultSet rstest = pstmt.executeQuery();