狂神說java超市管理系統dao層(增刪改查)
阿新 • • 發佈:2021-10-05
資料庫連線(增刪改查)
package dao; import com.mysql.jdbc.Connection; import java.io.IOException; import java.io.InputStream; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; public class BaseDao { privatestatic String driver; private static String url; private static String username; private static String pwd; //通過靜態載入器讀取配置檔案 static { InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties"); Properties properties = new Properties();try { properties.load(is); } catch (IOException e) { e.printStackTrace(); } driver = properties.getProperty("driver"); username = properties.getProperty("username"); url = properties.getProperty("url"); pwd = properties.getProperty("pwd"); }//通過靜態載入器連線資料庫 public static Connection GetConn() throws ClassNotFoundException, SQLException { Class.forName(driver ); Connection connection = (Connection) DriverManager.getConnection(url,username,pwd); return connection; } //查詢資料庫方法 public static ResultSet ExEc(Connection conn,String sql,Object[] params,PreparedStatement pr) throws SQLException{ pr = conn.clientPrepareStatement(sql); ResultSet rs=null; for (int i = 0; i <params.length ; i++) { pr.setObject(i+1,params[i]); } rs = pr.executeQuery(); return rs; } //增刪改查 public static int QuDel(Connection conn,String sql,Object[] params,PreparedStatement pr) throws SQLException{ pr = conn.clientPrepareStatement(sql); for (int i = 0; i <params.length ; i++) { pr.setObject(i+1,params[i]); } int up = pr.executeUpdate(); return up; } //關閉連線 public static boolean ConnClose(Connection conn, ResultSet rs,PreparedStatement pr){ boolean flag = true; if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); flag = false; } } if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); flag = false; } } if (pr != null) { try { pr.close(); } catch (SQLException e) { e.printStackTrace(); flag = false; } } return flag; } }
資料庫配置檔案
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=UTF8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true username=root pwd=123456