private void saveToDb() { Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(UPDATE_WARE); System.out.println(UPDATE_WARE); pstmt.setString(1, StringUtils.toChinese(this.Pname)); pstmt.setString(2, StringUtils.toChinese(this.Pmodel)); pstmt.setString(3, StringUtils.toChinese(this.Pcost)); pstmt.setString(4, StringUtils.toChinese(this.Pheft)); pstmt.setString(5, StringUtils.toChinese(this.Pfacturer)); pstmt.setString(6, StringUtils.toChinese(this.Pnote)); pstmt.setInt(7, this.Status); pstmt.setInt(8, this.Id); pstmt.executeUpdate(); } catch (SQLException sqle) { System.err.println("错误位置: DbWare.java:saveToDb(): " + sqle); sqle.printStackTrace(); } finally { try { pstmt.close(); } catch (Exception e) { e.printStackTrace(); } try { con.close(); } catch (Exception e) { e.printStackTrace(); } } }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter writer = response.getWriter(); HttpSession session = request.getSession(); String username = request.getParameter("username"); String password = request.getParameter("password"); String type = request.getParameter("type"); System.out.println(username + password + type); session.setAttribute("user", username); try { writer.println("<html>"); writer.println("<body bgcolor=green>"); writer.println("<center>"); ps.setString(1, username); ps.setString(2, password); ps.setString(3, type); ResultSet rs = ps.executeQuery(); if (rs.next()) { writer.println("<h1>LOGIN SUCCESSFUL</h1><br><br>"); writer.println("<a href=account.html>click here to see your account</a>"); } else { writer.println("<h1>LOGIN FAILED</h1><br><br>"); writer.println("<a href=login.html>click here to login again</a>"); } writer.println("</center>"); writer.println("</body>"); writer.println("</html>"); } catch (Exception e) { e.printStackTrace(); } }
public void save(Connection conn) throws SQLException { boolean is_new = isNew(); String query = (is_new ? ("insert into " + tableName() + " (" + recordIDColumnName() + ",mod_count,date_entered,date_modified,name,status,product) values (?,?,?,?,?,?,?)") : ("update " + tableName() + " set mod_count = ?, date_entered = ?, " + "date_modified = ?, name = ?, status = ?, product = ? where " + recordIDColumnName() + " = ?")); int idx = 1; PreparedStatement ps = conn.prepareStatement(query); if (is_new) { ps.setInt(idx++, getId().intValue()); } int new_mod_count = mod_count.intValue() + 1; ps.setInt(idx++, new_mod_count); ps.setTimestamp(idx++, date_entered); ps.setTimestamp(idx++, date_modified); // ---TODO: set to current time ps.setString(idx++, getName()); ps.setString(idx++, getStatus()); ps.setInt(idx++, getProduct().getId().intValue()); if (!is_new) { ps.setInt(idx++, getId().intValue()); } ps.executeUpdate(); ps.close(); // Only increment the mod_count if there was no exception during the save. setModCount(new Integer(new_mod_count)); }
private void goodB2G_sink(String data, HttpServletRequest request, HttpServletResponse response) throws Throwable { String names[] = data.split("-"); int iSuccess = 0; Logger log2 = Logger.getLogger("local-logger"); Connection conn_tmp2 = null; PreparedStatement sqlstatement = null; try { /* FIX: use prepared sqlstatement */ conn_tmp2 = IO.getDBConnection(); sqlstatement = conn_tmp2.prepareStatement("update users set hitcount=hitcount+1 where name=?"); for (int i = 0; i < names.length; ++i) { sqlstatement.setString(1, names[i]); sqlstatement.addBatch(); } int dbResults[] = sqlstatement.executeBatch(); for (int i = 0; i < names.length; ++i) { if (dbResults[i] > 0) { iSuccess++; } } IO.writeString("Succeeded in " + iSuccess + " out of " + names.length + " queries."); } catch (SQLException se) { log2.warning("Error getting database connection"); } finally { try { if (sqlstatement != null) { sqlstatement.close(); } } catch (SQLException e) { log2.warning("Error closing sqlstatement"); } finally { try { if (conn_tmp2 != null) { conn_tmp2.close(); } } catch (SQLException e) { log2.warning("Error closing conn_tmp2"); } } } }
/* goodB2G1() - use badsource and goodsink by changing second IO.STATIC_FINAL_FIVE==5 to IO.STATIC_FINAL_FIVE!=5 */ private void goodB2G1() throws Throwable { String data; if (IO.STATIC_FINAL_FIVE == 5) { /* get environment variable ADD */ /* POTENTIAL FLAW: Read data from an environment variable */ data = System.getenv("ADD"); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (IO.STATIC_FINAL_FIVE != 5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.writeLine("Benign, fixed string"); } else { if (data != null) { String names[] = data.split("-"); int successCount = 0; Connection dbConnection = null; PreparedStatement sqlStatement = null; try { /* FIX: Use prepared statement and executeBatch (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement("update users set hitcount=hitcount+1 where name=?"); for (int i = 0; i < names.length; i++) { sqlStatement.setString(1, names[i]); sqlStatement.addBatch(); } int resultsArray[] = sqlStatement.executeBatch(); for (int i = 0; i < names.length; i++) { if (resultsArray[i] > 0) { successCount++; } } IO.writeLine("Succeeded in " + successCount + " out of " + names.length + " queries."); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } }
/* goodB2G1() - use badsource and goodsink by changing second IO.staticTrue to IO.staticFalse */ private void goodB2G1() throws Throwable { String data; if (IO.staticTrue) { /* get environment variable ADD */ /* POTENTIAL FLAW: Read data from an environment variable */ data = System.getenv("ADD"); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (IO.staticFalse) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.writeLine("Benign, fixed string"); } else { Connection dbConnection = null; PreparedStatement sqlStatement = null; ResultSet resultSet = null; try { /* FIX: Use prepared statement and executeQuery (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement("select * from users where name=?"); sqlStatement.setString(1, data); resultSet = sqlStatement.executeQuery(); IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */ } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (resultSet != null) { resultSet.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql); } try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } }
/* goodB2G2() - use badsource and goodsink by reversing statements in second if */ private void goodB2G2(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; if (privateFive == 5) { data = ""; /* initialize data in case id is not in query string */ /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParameter()) */ { StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&"); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); /* a token will be like "id=foo" */ if (token.startsWith("id=")) /* check if we have the "id" parameter" */ { data = token.substring(3); /* set data to "foo" */ break; /* exit while loop */ } } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (privateFive == 5) { Connection dbConnection = null; PreparedStatement sqlStatement = null; try { /* FIX: Use prepared statement and execute (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement( "insert into users (status) values ('updated') where name=?"); sqlStatement.setString(1, data); Boolean result = sqlStatement.execute(); if (result) { IO.writeLine("Name, " + data + ", updated successfully"); } else { IO.writeLine("Unable to update records for user: "******"Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } }
private void insertLog(HttpServletRequest req, Connection connection) throws SQLException { try (PreparedStatement stmt = connection.prepareStatement("INSERT INTO LOGGING (date,ip,url) VALUES (?,?,?)")) { stmt.setTimestamp(1, new Timestamp((new java.util.Date()).getTime())); stmt.setString(2, req.getRemoteAddr()); stmt.setString(3, req.getRequestURI()); stmt.executeUpdate(); } }
/* goodB2G1() - use badsource and goodsink by changing second privateTrue to privateFalse */ private void goodB2G1(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; if (privateTrue) { /* POTENTIAL FLAW: Read data from a querystring using getParameter */ data = request.getParameter("name"); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (privateFalse) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.writeLine("Benign, fixed string"); } else { Connection dbConnection = null; PreparedStatement sqlStatement = null; try { /* FIX: Use prepared statement and execute (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement( "insert into users (status) values ('updated') where name=?"); sqlStatement.setString(1, data); Boolean result = sqlStatement.execute(); if (result) { IO.writeLine("Name, " + data + ", updated successfully"); } else { IO.writeLine("Unable to update records for user: "******"Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } }
private void insertIntoDb() { Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(INSERT_WARE); pstmt.setInt(1, this.Id); pstmt.setString(2, StringUtils.toChinese(this.Pname)); pstmt.setString(3, StringUtils.toChinese(this.Pmodel)); pstmt.setString(4, StringUtils.toChinese(this.Pcost)); pstmt.setString(5, StringUtils.toChinese(this.Pheft)); pstmt.setString(6, StringUtils.toChinese(this.Pfacturer)); pstmt.setString(7, StringUtils.toChinese(this.Pnote)); pstmt.setString(8, StringUtils.toChinese(this.Createdate)); pstmt.setInt(9, this.Status); pstmt.executeUpdate(); } catch (SQLException sqle) { System.err.println("错误位置: Dbware:insertIntoDb()-" + sqle); sqle.printStackTrace(); } finally { try { pstmt.close(); } catch (Exception e) { e.printStackTrace(); } try { con.close(); } catch (Exception e) { e.printStackTrace(); } } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); Connection conn = null; PreparedStatement pstmt = null; try { System.out.println("Enrollno: 130050131049"); // STEP 2: Register JDBC driver Class.forName(JDBC_DRIVER); // STEP 3: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); // STEP 2: Executing query String sql = "SELECT * FROM logindetails WHERE name = ?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, "Krut"); ResultSet rs = pstmt.executeQuery(); out.print("| <b>Name</b>| "); out.print("<b>Password</b>| "); out.println("</br>\n-------------------------------</br>"); while (rs.next()) { out.println(); out.print("| " + rs.getString(1)); out.print("| " + rs.getString(2) + "|"); out.println("</br>"); } } catch (SQLException se) { // Handle errors for JDBC se.printStackTrace(); } catch (Exception e) { // Handle errors for Class.forName e.printStackTrace(); } finally { // finally block used to close resources try { if (pstmt != null) conn.close(); } catch (SQLException se) { } // do nothing try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } // end finally try } // end try }
/* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */ public void goodB2G1Sink(String data) throws Throwable { if (CWE89_SQL_Injection__Environment_executeBatch_22a.goodB2G1PublicStatic) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } else { if (data != null) { String names[] = data.split("-"); int successCount = 0; Connection dbConnection = null; PreparedStatement sqlStatement = null; try { /* FIX: Use prepared statement and executeBatch (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement("update users set hitcount=hitcount+1 where name=?"); for (int i = 0; i < names.length; i++) { sqlStatement.setString(1, names[i]); sqlStatement.addBatch(); } int resultsArray[] = sqlStatement.executeBatch(); for (int i = 0; i < names.length; i++) { if (resultsArray[i] > 0) { successCount++; } } IO.writeLine("Succeeded in " + successCount + " out of " + names.length + " queries."); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } }
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection con = DriverManager.getConnection(Utility.connection, Utility.username, Utility.password); String email = request.getParameter("email_id"); String number = ""; boolean exists = false; String user_name = ""; int user_id = -1; String str1 = "SELECT USER_ID,NAME,PHONE_NUMBER FROM USERS WHERE EMAIL_ID=?"; PreparedStatement prep1 = con.prepareStatement(str1); prep1.setString(1, email); ResultSet rs1 = prep1.executeQuery(); if (rs1.next()) { exists = true; user_id = rs1.getInt("USER_ID"); user_name = rs1.getString("NAME"); number = rs1.getString("PHONE_NUMBER"); } int verification = 0; JSONObject data = new JSONObject(); if (exists) { verification = (int) (Math.random() * 9535641 % 999999); System.out.println("Number " + number + "\nVerification: " + verification); SMSProvider.sendSMS( number, "Your One Time Verification Code for PeopleConnect Is " + verification); } data.put("user_name", user_name); data.put("user_id", user_id); data.put("verification_code", "" + verification); data.put("phone_number", number); String toSend = data.toJSONString(); out.print(toSend); System.out.println(toSend); } catch (Exception e) { e.printStackTrace(); } finally { out.close(); } }
/* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */ public void goodB2G1Sink(String data) throws Throwable { if (CWE89_SQL_Injection__connect_tcp_executeQuery_22a.goodB2G1PublicStatic) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } else { Connection dbConnection = null; PreparedStatement sqlStatement = null; ResultSet resultSet = null; try { /* FIX: Use prepared statement and executeQuery (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement("select * from users where name=?"); sqlStatement.setString(1, data); resultSet = sqlStatement.executeQuery(); IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */ } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (resultSet != null) { resultSet.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql); } try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } }
/* goodB2G2() - use badsource and goodsink by reversing statements in second if */ private void goodB2G2() throws Throwable { String data; if (PRIVATE_STATIC_FINAL_TRUE) { /* get environment variable ADD */ /* POTENTIAL FLAW: Read data from an environment variable */ data = System.getenv("ADD"); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (PRIVATE_STATIC_FINAL_TRUE) { Connection dbConnection = null; PreparedStatement sqlStatement = null; try { /* FIX: Use prepared statement and execute (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement( "insert into users (status) values ('updated') where name=?"); sqlStatement.setString(1, data); Boolean result = sqlStatement.execute(); if (result) { IO.writeLine("Name, " + data + ", updated successfully"); } else { IO.writeLine("Unable to update records for user: "******"Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } }
private void goodB2G1Sink(String data) throws Throwable { if (goodB2G1Private) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.writeLine("Benign, fixed string"); } else { Connection dbConnection = null; PreparedStatement sqlStatement = null; ResultSet resultSet = null; try { /* FIX: Use prepared statement and executeQuery (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement("select * from users where name=?"); sqlStatement.setString(1, data); resultSet = sqlStatement.executeQuery(); IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */ } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (resultSet != null) { resultSet.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql); } try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } }
/* goodB2G() - use badsource and goodsink */ public void goodB2G_sink(String data, HttpServletRequest request, HttpServletResponse response) throws Throwable { Logger log2 = Logger.getLogger("local-logger"); Connection conn_tmp2 = null; PreparedStatement sqlstatement = null; ResultSet sqlrs = null; try { /* FIX: use prepared sqlstatement */ conn_tmp2 = IO.getDBConnection(); sqlstatement = conn_tmp2.prepareStatement("select * from users where name=?"); sqlstatement.setString(1, data); sqlrs = sqlstatement.executeQuery(); IO.writeString(sqlrs.toString()); } catch (SQLException se) { log2.warning("Error getting database connection"); } finally { try { if (sqlrs != null) { sqlrs.close(); } } catch (SQLException e) { log2.warning("Error closing sqlrs"); } finally { try { if (sqlstatement != null) { sqlstatement.close(); } } catch (SQLException e) { log2.warning("Error closing sqlstatement"); } finally { try { if (conn_tmp2 != null) { conn_tmp2.close(); } } catch (SQLException e) { log2.warning("Error closing conn_tmp2"); } } } } }
private void goodB2G1Sink(String data) throws Throwable { if (goodB2G1Private) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.writeLine("Benign, fixed string"); } else { Connection dbConnection = null; PreparedStatement sqlStatement = null; try { /* FIX: Use prepared statement and execute (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement( "insert into users (status) values ('updated') where name=?"); sqlStatement.setString(1, data); Boolean result = sqlStatement.execute(); if (result) { IO.writeLine("Name, " + data + ", updated successfully"); } else { IO.writeLine("Unable to update records for user: "******"Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } }
public void action(String data, HttpServletRequest request, HttpServletResponse response) throws Throwable { if (data != null) { String names[] = data.split("-"); int successCount = 0; Connection dbConnection = null; PreparedStatement sqlStatement = null; try { /* FIX: Use prepared statement and executeBatch (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement("update users set hitcount=hitcount+1 where name=?"); for (int i = 0; i < names.length; i++) { sqlStatement.setString(1, names[i]); sqlStatement.addBatch(); } int resultsArray[] = sqlStatement.executeBatch(); for (int i = 0; i < names.length; i++) { if (resultsArray[i] > 0) { successCount++; } } IO.writeLine("Succeeded in " + successCount + " out of " + names.length + " queries."); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } }
/* goodB2G() - use BadSource and GoodSink */ public void goodB2GSink(HashMap<Integer, String> dataHashMap) throws Throwable { String data = dataHashMap.get(2); Connection dbConnection = null; PreparedStatement sqlStatement = null; ResultSet resultSet = null; try { /* FIX: Use prepared statement and executeQuery (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement("select * from users where name=?"); sqlStatement.setString(1, data); resultSet = sqlStatement.executeQuery(); IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */ } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (resultSet != null) { resultSet.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql); } try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } }
private void goodB2G() throws Throwable { String data = goodB2G_source(); Logger log2 = Logger.getLogger("local-logger"); Connection conn_tmp2 = null; PreparedStatement sqlstatement = null; try { /* FIX: use prepared sqlstatements */ conn_tmp2 = IO.getDBConnection(); sqlstatement = conn_tmp2.prepareStatement("insert into users (status) values ('updated') where name=?"); sqlstatement.setString(1, data); Boolean bResult = sqlstatement.execute(); if (bResult) { IO.writeString("Name, " + data + ", updated successfully"); } else { IO.writeString("Unable to update records for user: "******"Error getting database connection"); } finally { try { if (sqlstatement != null) { sqlstatement.close(); } } catch (SQLException e) { log2.warning("Error closing sqlstatement"); } finally { try { if (conn_tmp2 != null) { conn_tmp2.close(); } } catch (SQLException e) { log2.warning("Error closing conn_tmp2"); } } } }
/* goodB2G() - use BadSource and GoodSink */ public void goodB2GSink(LinkedList<String> dataLinkedList) throws Throwable { String data = dataLinkedList.remove(2); Connection dbConnection = null; PreparedStatement sqlStatement = null; try { /* FIX: Use prepared statement and execute (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement( "insert into users (status) values ('updated') where name=?"); sqlStatement.setString(1, data); Boolean result = sqlStatement.execute(); if (result) { IO.writeLine("Name, " + data + ", updated successfully"); } else { IO.writeLine("Unable to update records for user: "******"Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } }
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { Driver driver = new com.mysql.jdbc.Driver(); DriverManager.registerDriver(driver); Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1/school", "root", "password"); PreparedStatement preparedStatement = connection.prepareStatement("update student set name=?, per=? where roll=?"); preparedStatement.setString(1, request.getParameter("name")); preparedStatement.setFloat(2, Float.parseFloat(request.getParameter("per"))); preparedStatement.setInt(3, Integer.parseInt(request.getParameter("roll"))); preparedStatement.execute(); preparedStatement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Display"); requestDispatcher.forward(request, response); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // I use "session" in order to throws the object named user bean. HttpSession session = request.getSession(true); response.setContentType("text/html"); request.setCharacterEncoding("UTF-8"); UserBean ub = (UserBean) session.getAttribute("user"); if (ub == null) { String haveLogin = "******"; session.setAttribute("haveLogin", haveLogin); response.sendRedirect("cart"); } else { String mID = ub.getmID(); String iID = (String) request.getParameter("iID"); // String idx = (String)request.getParameter("idx"); Connection conn = null; try { // Getting the connection from database. Class.forName("com.mysql.jdbc.Driver"); /*conn = DriverManager .getConnection("jdbc:mysql://localhost/se?" + "user=root");*/ conn = DriverManager.getConnection( "jdbc:mysql://localhost/user_register?" + "user=sqluser&password=sqluserpw&useUnicode=true&characterEncoding=UTF-8"); String sql = "delete from cart_item_mapping where mID=? and iID = ?"; PreparedStatement pst = conn.prepareStatement(sql); // Using preparedstatement by set the parameter related to "?" symbol. pst.setString(1, mID); pst.setString(2, iID); pst.executeUpdate(); pst.close(); response.sendRedirect("ShowCartController"); } catch (Exception e) { e.printStackTrace(); } } }
public void doGet(HttpServletRequest request, HttpServletResponse response) { try { String comment = request.getParameter("comment"); int answerId = Integer.parseInt(request.getParameter("answer_id")); Connection connection = GlobalResources.getConnection(); Statement s; s = connection.createStatement(); PreparedStatement preparedStatement; PreparedStatement preparedStatement1; preparedStatement = connection.prepareStatement("insert into comment(comment,answer_id) values(?,?)"); preparedStatement.setString(1, comment); preparedStatement.setInt(2, answerId); preparedStatement.executeUpdate(); preparedStatement.close(); connection.close(); RequestDispatcher requestDispatcher; requestDispatcher = request.getRequestDispatcher("/studenthome.jsp"); requestDispatcher.forward(request, response); } catch (Exception e) { } }
/* goodB2G() - use badsource and goodsink */ private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data = (new CWE89_SQL_Injection__getQueryString_Servlet_executeUpdate_61b()) .goodB2GSource(request, response); Connection dbConnection = null; PreparedStatement sqlStatement = null; try { /* FIX: Use prepared statement and executeUpdate (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement( "insert into users (status) values ('updated') where name=?"); sqlStatement.setString(1, data); int rowCount = sqlStatement.executeUpdate(); IO.writeLine("Updated " + rowCount + " rows successfully."); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } }
/* goodB2G() - use badsource and goodsink */ public void goodB2G_sink(Object data_obj) throws Throwable { String data = (String) data_obj; Logger log2 = Logger.getLogger("local-logger"); Connection conn_tmp2 = null; PreparedStatement sqlstatement = null; try { /* FIX: use prepared sqlstatement */ conn_tmp2 = IO.getDBConnection(); sqlstatement = conn_tmp2.prepareStatement("insert into users (status) values ('updated') where name=?"); sqlstatement.setString(1, data); int iResult = sqlstatement.executeUpdate(); IO.writeString("Updated " + iResult + " rows successfully."); } catch (SQLException se) { log2.warning("Error getting database connection"); } finally { try { if (sqlstatement != null) { sqlstatement.close(); } } catch (SQLException e) { log2.warning("Error closing sqlstatement"); } finally { try { if (conn_tmp2 != null) { conn_tmp2.close(); } } catch (SQLException e) { log2.warning("Error closing conn_tmp2"); } } } }
/* goodB2G() - use badsource and goodsink */ public void goodB2GSink() throws Throwable { String data = CWE89_SQL_Injection__Environment_executeUpdate_68a.data; Connection dbConnection = null; PreparedStatement sqlStatement = null; try { /* FIX: Use prepared statement and executeUpdate (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement( "insert into users (status) values ('updated') where name=?"); sqlStatement.setString(1, data); int rowCount = sqlStatement.executeUpdate(); IO.writeLine("Updated " + rowCount + " rows successfully."); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } }
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); try { String username = request.getParameter("t1"); String password = request.getParameter("t2"); String email = request.getParameter("t4"); String college = request.getParameter("t5"); String phone = request.getParameter("t6"); String country = request.getParameter("t7"); String languages = request.getParameter("t8"); Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "tiger"); PreparedStatement pst = con.prepareStatement("insert into stu_tab values(?,?,?,?,?,?,?)"); pst.setString(1, username); pst.setString(2, password); pst.setString(3, email); pst.setString(4, college); pst.setString(5, phone); pst.setString(6, country); pst.setString(7, languages); int i = pst.executeUpdate(); if (i != 0) { out.println("<html><body align=center bgcolor=#C0C0C0 text=black>"); out.println("<h3>!.. Registration Successful !..</h3>"); out.println( "<a href=Slogin1.html style=text-decoration:none>click here</a> to go back to login page"); out.println("</body></html>"); } else { out.println("<html><body align=center bgcolor=#C0C0C0 text=black>"); out.println("<h3>!.. Registration Failed !..</h3>"); out.println( "<a href=Slogin1.html style=text-decoration:none>click here</a> to go back to login page"); out.println("</body></html>"); } } catch (Exception e) { out.println(e); } }
/** Business logic to execute. */ public final Response executeCommand( Object inputPar, UserSessionParameters userSessionPars, HttpServletRequest request, HttpServletResponse response, HttpSession userSession, ServletContext context) { String serverLanguageId = ((JAIOUserSessionParameters) userSessionPars).getServerLanguageId(); Connection conn = null; PreparedStatement pstmt = null; try { conn = ConnectionManager.getConnection(context); // fires the GenericEvent.CONNECTION_CREATED event... EventsManager.getInstance() .processEvent( new GenericEvent( this, getRequestName(), GenericEvent.CONNECTION_CREATED, (JAIOUserSessionParameters) userSessionPars, request, response, userSession, context, conn, inputPar, null)); ArrayList oldVOs = ((ArrayList[]) inputPar)[0]; ArrayList newVOs = ((ArrayList[]) inputPar)[1]; RoleFunctionCompanyVO oldVO = null; RoleFunctionCompanyVO newVO = null; Response res = null; for (int i = 0; i < oldVOs.size(); i++) { oldVO = (RoleFunctionCompanyVO) oldVOs.get(i); newVO = (RoleFunctionCompanyVO) newVOs.get(i); if (!oldVO.getCanView().booleanValue()) { // no record in SYS02 yet... if (newVO.getCanView().booleanValue()) { pstmt = conn.prepareStatement( "insert into SYS02_COMPANIES_ACCESS(PROGRESSIVE_SYS04,FUNCTION_CODE_SYS06,CAN_INS,CAN_UPD,CAN_DEL,COMPANY_CODE_SYS01) " + "values(?,?,?,?,?,?)"); pstmt.setBigDecimal(1, newVO.getProgressiveSys04SYS02()); pstmt.setString(2, newVO.getFunctionCodeSys06SYS02()); pstmt.setString(3, newVO.getCanInsSYS02().booleanValue() ? "Y" : "N"); pstmt.setString(4, newVO.getCanUpdSYS02().booleanValue() ? "Y" : "N"); pstmt.setString(5, newVO.getCanDelSYS02().booleanValue() ? "Y" : "N"); pstmt.setString(6, newVO.getCompanyCodeSys01SYS02()); pstmt.execute(); } } else { // record already exists in SYS02... if (newVO.getCanView().booleanValue()) { // record in SYS02 will be updated... pstmt = conn.prepareStatement( "update SYS02_COMPANIES_ACCESS set CAN_INS=?,CAN_UPD=?,CAN_DEL=? where " + "PROGRESSIVE_SYS04=? and FUNCTION_CODE_SYS06=? and COMPANY_CODE_SYS01=? "); pstmt.setString(1, newVO.getCanInsSYS02().booleanValue() ? "Y" : "N"); pstmt.setString(2, newVO.getCanUpdSYS02().booleanValue() ? "Y" : "N"); pstmt.setString(3, newVO.getCanDelSYS02().booleanValue() ? "Y" : "N"); pstmt.setBigDecimal(4, newVO.getProgressiveSys04SYS02()); pstmt.setString(5, newVO.getFunctionCodeSys06SYS02()); pstmt.setString(6, newVO.getCompanyCodeSys01SYS02()); pstmt.execute(); } else { // delete record from SYS02... pstmt = conn.prepareStatement( "delete from SYS02_COMPANIES_ACCESS where PROGRESSIVE_SYS04=? and FUNCTION_CODE_SYS06=? and COMPANY_CODE_SYS01=?"); pstmt.setBigDecimal(1, newVO.getProgressiveSys04SYS02()); pstmt.setString(2, newVO.getFunctionCodeSys06SYS02()); pstmt.setString(3, newVO.getCompanyCodeSys01SYS02()); pstmt.execute(); } } } Response answer = new VOListResponse(newVOs, false, newVOs.size()); // fires the GenericEvent.BEFORE_COMMIT event... EventsManager.getInstance() .processEvent( new GenericEvent( this, getRequestName(), GenericEvent.BEFORE_COMMIT, (JAIOUserSessionParameters) userSessionPars, request, response, userSession, context, conn, inputPar, answer)); conn.commit(); // fires the GenericEvent.AFTER_COMMIT event... EventsManager.getInstance() .processEvent( new GenericEvent( this, getRequestName(), GenericEvent.AFTER_COMMIT, (JAIOUserSessionParameters) userSessionPars, request, response, userSession, context, conn, inputPar, answer)); return answer; } catch (Throwable ex) { Logger.error( userSessionPars.getUsername(), this.getClass().getName(), "executeCommand", "Error while updating company-role-function settings", ex); try { pstmt.close(); } catch (Exception ex2) { } try { conn.rollback(); } catch (Exception ex3) { } return new ErrorResponse(ex.getMessage()); } finally { try { ConnectionManager.releaseConnection(conn, context); } catch (Exception ex1) { } } }