连接工具:
package db; import java.sql.*; public class MovieDb { private static final String URL = "jdbc:mysql://xxxx:3306/xxx?autoReconnect=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false"; private static final String UNAME = "xxx"; private static final String PWD = "xx"; private static Connection conn = null; static { try { // 1.加载驱动程序 Class.forName("com.mysql.cj.jdbc.Driver"); // 2.获得数据库的连接 conn = DriverManager.getConnection(URL, UNAME, PWD); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public static Connection getConnection() { return conn; } public static void closeConnection(Connection conn, PreparedStatement pstmt, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (Exception e) { e.printStackTrace(); } } if (pstmt != null) { try { pstmt.close(); } catch (Exception e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } } }
使用方法:
package deal; import db.MovieDb; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MovieDeal { public static List<Map> getToday() { List<Map> movies = new ArrayList<Map>(); Connection movieConn = null; PreparedStatement moviePs = null; ResultSet movieRs = null; try { movieConn = MovieDb.getConnection(); moviePs = movieConn.prepareStatement("sql"); movieRs = moviePs.executeQuery(); while (movieRs.next()) { Map<String,String> map = new HashMap<String, String>(); map.put("type_name",movieRs.getString("type_name")); movies.add(map); } } catch (Exception e) { e.printStackTrace(); } finally { MovieDb.closeConnection(movieConn, moviePs, movieRs); } return movies; } }