package com.src.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * * */ public class Sqltools { private static Connection cnn = null; private static PreparedStatement ps = null; private static ResultSet rs = null; private static String url = "jdbc:mysql://localhost:3306/sport"; private static String username = "root"; private static String password = "123456"; private static String driver = "com.mysql.cj.jdbc.Driver";// static { try { Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() { try { cnn = DriverManager.getConnection(url, username, password); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return cnn; } public static ResultSet excuteQuery(String sql, String[] parameters) { try { cnn = getConnection(); ps = cnn.prepareStatement(sql); if (parameters != null && !parameters.equals("")) { for (int i = 0; i < parameters.length; i++) { ps.setString(i + 1, parameters[i]); } } rs = ps.executeQuery(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return rs; } /** * * * * @param sql * @param parameters */ public static boolean excuteUpdates(String sql, String[] parameters) { boolean b=true; try { cnn = getConnection(); ps = cnn.prepareStatement(sql); if (parameters != null && !parameters.equals("")) { for (int i = 0; i < parameters.length; i++) { ps.setString(i + 1, parameters[i]); } } ps.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); b=false; throw new RuntimeException(e.getMessage()); }finally{ close(null,ps,cnn); } return b; } /** * * * @param rs * @param ps * @param cnn */ public static void close(ResultSet rs, PreparedStatement ps, Connection cnn) { if (rs != null) { try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } rs = null; } if (ps != null) { try { ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } ps = null; } if (cnn != null) { try { cnn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } cnn = null; } } /** * * * * @return */ public static Connection getCnn() { return cnn; } public static PreparedStatement getPs() { return ps; } public static ResultSet getRs() { return rs; } }