Skip to content

Instantly share code, notes, and snippets.

@DhavalDalal
Last active February 18, 2022 10:09
Show Gist options
  • Save DhavalDalal/5f75234c9f296290db61501f92c3faef to your computer and use it in GitHub Desktop.
Save DhavalDalal/5f75234c9f296290db61501f92c3faef to your computer and use it in GitHub Desktop.
Smelly JDBC Code

Smelly JDBC Code (Java)

public class Employee {
private final Integer id;
private final String name;
public Employee(final Integer id, final String name) {
this.id = id;
this.name = name;
}
public String toString() {
return String.format("Employee(%d, %s)", id, name);
}
}
import java.sql.*;
import java.util.*;
public class Sql {
static List<Employee> execute(String dburl, String sql) throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
List<Employee> employees = new ArrayList<Employee>();
try {
connection = DriverManager.getConnection(dburl);
statement = connection.createStatement();
statement.execute(sql);
resultSet = statement.getResultSet();
while (resultSet.next()) {
int empId = resultSet.getInt(0);
String name = resultSet.getString(1);
employees.add(new Employee(empId, name));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
if (statement != null) {
statement.close();
if (resultSet != null)
resultSet.close();
}
}
}
return employees;
}
public static void main(String args[]) throws ClassNotFoundException {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test";
List<Employee> employees = Sql.execute(url,"select * from employee");
System.out.println("employees = " + employees);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment