如何将Spring与JDBC集成? [英] How to integrate Spring with JDBC?

查看:159
本文介绍了如何将Spring与JDBC集成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用以下代码连接到mysql数据库,但是项目经理声明我必须使用Spring框架来处理连接.

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.

我怎么能做到这一点?

使用Spring处理数据库连接是否会提高整个系统的质量?

And would the use of Spring to handle the database connections improve the quality of the overall system?

这里是班上的一个例子

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);
   }
}

}

推荐答案

Spring参考指南提供了

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:

  • 消除很多样板代码,
  • 具有忘记关闭语句和连接的功能,
  • 减轻对不适当的异常处理的诱惑,
  • 非常容易摆脱低效的连接处理.

您显示的代码受这四个方面的困扰,所以我不得不说切换到Spring将为您带来巨大的好处.

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.

此外,如果您使用的是多线程应用程序(所有Web应用程序都是多线程的),请在列表中添加自动线程安全",这也是您的代码所缺少的.

Also, if you're in a multithreaded app (all webapps are multithreaded), add "automatic thread-safety" to the list, which your code also lacks.

这篇关于如何将Spring与JDBC集成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆