Reputation: 435
I am currently using the following code to connect to a mysql database, but the project manager states I must make use of Spring framework to handle the connections.
How am I able to achive this?
And would the use of Spring to handle the database connections improve the quality of the overall system?
Here is an example of the class
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
public class SomeClass {
Connection connection = null;
ResultSet resultSet;
Statement state;
ArrayList aList = new ArrayList();
public void connectToDatabase(String databaseName)
{
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = (Connection) DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/" + databaseName, "username", "password");
state = (Statement) connection.createStatement();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
private void populateAList() {
try
{
connectToTable("testDB");
resultSet = state.executeQuery("SELECT listItems FROM tblListItems WHERE ID = '" + theIDYouWant + "'");
while(resultSet.next())
{
aList.add(resultSet.getString("listItems"));
}
resultSet.close();
state.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
}
Upvotes: 0
Views: 549
Reputation: 128799
The Spring Reference Guide offers detailed documentation of its support for JDBC. At the bare minimum, using a JdbcTemplate--which requires nothing from you but new JdbcTemplate(...)
for the most basic usage--would:
The code you've shown suffers from all four of these, so I'd have to say that switching to Spring would be a huge benefit for you.
Also, if you're in a multithreaded app (all webapps are multithreaded), add "automatic thread-safety" to the list, which your code also lacks.
Upvotes: 3