Skip to content
This repository has been archived by the owner on Dec 15, 2020. It is now read-only.

Sample code leaks resources and does not use best practice of prepared statements #13

Open
nicenemo opened this issue Feb 1, 2018 · 0 comments

Comments

@nicenemo
Copy link

nicenemo commented Feb 1, 2018

Code at : https://docs.microsoft.com/nl-nl/azure/sql-database/sql-database-connect-query-java

  • The code does not use try with resources /does not try to close connections in a finally clause.
  • It does not use prepared statements

Code I saw at 25-01-2018

public static void main(String[] args) {

     // Connect to database
        String hostName = "your_server.database.windows.net";
        String dbName = "your_database";
        String user = "your_username";
        String password = "your_password";
        String url = String.format("jdbc:sqlserver://%s:1433;database=%s;user=%s;password=%s;encrypt=true;hostNameInCertificate=*.database.windows.net;loginTimeout=30;", hostName, dbName, user, password);
        Connection connection = null;

        try {
                connection = DriverManager.getConnection(url);
                String schema = connection.getSchema();
                System.out.println("Successful connection - Schema: " + schema);

                System.out.println("Query data example:");
                System.out.println("=========================================");

                // Create and execute a SELECT SQL statement.
                String selectSql = "SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName " 
                    + "FROM [SalesLT].[ProductCategory] pc "  
                    + "JOIN [SalesLT].[Product] p ON pc.productcategoryid = p.productcategoryid";

                try (Statement statement = connection.createStatement();
                    ResultSet resultSet = statement.executeQuery(selectSql)) {

                        // Print results from select statement
                        System.out.println("Top 20 categories:");
                        while (resultSet.next())
                        {
                            System.out.println(resultSet.getString(1) + " "
                                + resultSet.getString(2));
                        }
                 connection.close();
                }                   
        }
        catch (Exception e) {
                e.printStackTrace();
        }
    }
}
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant