diff --git a/GDMS.iml b/GDMS.iml index 4bde68d..4c713fc 100644 --- a/GDMS.iml +++ b/GDMS.iml @@ -29,6 +29,5 @@ - \ No newline at end of file diff --git a/src/dao/DBManagement.java b/src/dao/DBManagement.java index e597616..d8718a4 100644 --- a/src/dao/DBManagement.java +++ b/src/dao/DBManagement.java @@ -1,10 +1,6 @@ package dao; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Properties; +import java.sql.*; import org.apache.tomcat.jdbc.pool.DataSource; import org.apache.tomcat.jdbc.pool.PoolProperties; @@ -19,20 +15,24 @@ public class DBManagement { public static DataSource dataSource = new DataSource(); - public void init(){ + private static boolean ifInit = false; + + public static void init(){ PoolProperties poolProperties = new PoolProperties(); poolProperties.setUrl(url); poolProperties.setDriverClassName(driverClassName); poolProperties.setUsername(username); poolProperties.setPassword(password); dataSource.setPoolProperties(poolProperties); - } - public static Connection getConnection(){ try { Class.forName(driverClassName); } catch (ClassNotFoundException e) { e.printStackTrace(); } + ifInit = true; + } + public static Connection getConnection(){ + if(!ifInit) return null; try { return DriverManager.getConnection(url,username,password); } catch (SQLException e) { @@ -40,4 +40,45 @@ public class DBManagement { } return null; } + + public static ResultSet query(String sql) { + if(!ifInit) return null; + ResultSet rs = null; + Connection con = null; + try{ + con = DBManagement.getConnection(); + Statement stmt = con.createStatement(); + rs = stmt.executeQuery(sql); + } catch (SQLException e) { + e.printStackTrace(); + }finally { + if(con!=null) { + try { + con.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } + return rs; + } + public static void update(String sql) { + if(!ifInit) return; + Connection con = null; + try{ + con = DBManagement.getConnection(); + Statement stmt = con.createStatement(); + stmt.executeUpdate(sql); + } catch (SQLException e) { + e.printStackTrace(); + }finally { + if(con!=null) { + try { + con.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } + } } diff --git a/src/init/Init.java b/src/init/Init.java index dfc60d4..3d42bad 100644 --- a/src/init/Init.java +++ b/src/init/Init.java @@ -13,7 +13,7 @@ import java.io.IOException; @WebServlet(name = "Init") public class Init extends HttpServlet { public void init(){ - new DBManagement().init(); + DBManagement.init(); new test(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {