package webPractice; import java.io.InputStream; import java.sql.*; import java.util.Properties; public class JDBCTools { public static Connection getConnection() throws Exception{ Properties properties = new Properties(); InputStream in = JDBCTools.class.getClassLoader().getResourceAsStream("jdbc.properties"); properties.load(in); String driver = properties.getProperty("driver"); String url = properties.getProperty("url"); String user = properties.getProperty("user"); String password = properties.getProperty("password"); Class.forName(driver); Connection connection = DriverManager.getConnection(url, user, password); return connection; } /* 包括INSERT DELETE UPDATE 但是不包括SELECT 所以不需要返回值 */ public static void update(String sql, Object ...args){ Connection connection = null; PreparedStatement ps = null; try { connection = getConnection(); ps = connection.prepareStatement(sql); for(int i = 0; i < args.length; i++){ ps.setObject(i + 1, args[i]); } ps.executeUpdate(); }catch(Exception e){ e.printStackTrace(); }finally{ if(ps!= null){ try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if(connection != null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } /* SELECT */ public static String[] resultSet(String sql){ String[] res = new String[2]; Connection connection = null; PreparedStatement ps = null; ResultSet resultSet = null; // ResultSetMetaData resultSetMetaData = null; try{ connection = getConnection(); ps = connection.prepareStatement(sql); resultSet = ps.executeQuery(); //resultSetMetaData = resultSet.getMetaData(); if(resultSet.next()){ res[0]= resultSet.getString(1); res[1]= resultSet.getString(2); } }catch(Exception e){ e.printStackTrace(); }finally{ if(resultSet != null){ try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if(ps!= null){ try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if(connection != null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } return res; } }
url=jdbc:mysql://localhost:3306/db_person user=root password=1234 driver=com.mysql.jdbc.Driver