日期:2014-05-16 浏览次数:20483 次
public class ConnectionManager { private static String DRIVER_CLASS = "net.sourceforge.jtds.jdbc.Driver"; private static String URL = "jdbc:jtds:sqlserver://localhost:1433/forums"; private static String USER_NAME = "sa"; private static String PASSWORD = "sa"; private ConnectionManager() { } //获取数据库连接对象的方法 public static Connection getConnection() { Connection conn = null; try { Class.forName(DRIVER_CLASS); conn = DriverManager.getConnection(URL, USER_NAME, PASSWORD); } catch(ClassNotFoundException e) { e.printStackTrace(); } catch(SQLException e) { e.printStackTrace(); } return conn; } public static void main(String[] args) { String sql = "SELECT * FROM userInfo"; List<UserInfo> list = new ArrayList<UserInfo>(); Connection conn = null; PreparedStatement stm = null; ResultSet result = null; conn = getConnection(); try { stm = conn.prepareStatement(sql); result = stm.executeQuery(); UserInfo temp; while (result.next()) { temp = new UserInfo(result.getInt("userId"), result.getString("userName"), result.getString("password")); list.add(temp); } } catch(SQLException e) { e.printStackTrace(); } finally { try { result.close(); stm.close(); conn.close(); } catch(SQLException e) { e.printStackTrace(); } finally { result = null; stm = null; conn = null; } } for (UserInfo temp : list) { System.out.println(temp.getUserId() + "--" + temp.getUserName() + "--" + temp.getPassword()); } } }