import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; public class JdbcCodeDao implements CodeDao { private static String driverClassName; //启动驱动 private static String url; //设置连接路径 private static String username; //数据库用户名 private static String password; //数据库连接密码 static{ readJdbcProperties(); } public static void readJdbcProperties() { Properties props = new Properties(); // 第一种,通过类加载器进行获取properties文件流--> // InputStream in = JdbcCodeDao.class.getClassLoader().getResourceAsStream("db.properties"); // 第二种,通过类进行获取properties文件流--> InputStream in = JdbcCodeDao.class.getResourceAsStream("/jdbc.properties"); try { props.load(in); driverClassName = props.getProperty("driver"); url = props.getProperty("url"); username = props.getProperty("username"); password = props.getProperty("password"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void add(Code form) { Connection con = null; //连接 PreparedStatement pstmt = null; //使用预编译语句 ResultSet rs = null; //获取的结果集 try { Class.forName(driverClassName); //执行驱动 con = DriverManager.getConnection(url, username, password); //获取连接 String sql = "INSERT INTO CODE VALUES(?,?)"; //设置的预编译语句格式 pstmt = con.prepareStatement(sql); pstmt.setString(1, form.getName()); pstmt.setString(2, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); pstmt.executeUpdate(); } catch (Exception e) { throw new RuntimeException(e); }finally { //关闭资源,倒关 try { if(rs != null) rs.close(); if(pstmt != null) pstmt.close(); if(con != null) con.close(); //必须要关 } catch (Exception e) { } } } @Override public Code findByName(String name) { // String driverClassName = "com.mysql.jdbc.Driver"; // String url = "jdbc:mysql://118.190.47.230:3306/ys_equipment_cs"; //设置连接路径 // String username = "root"; //数据库用户名 // String password = "p011430seya1026"; //数据库连接密码 Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { Class.forName(driverClassName); con = DriverManager.getConnection(url, username, password); String sql = "SELECT * FROM CODE WHERE name=?"; pstmt = con.prepareStatement(sql); pstmt.setNString(1, name); rs = pstmt.executeQuery(); if(rs == null) { return null; } if(rs.next()) { Code code = new Code(); code.setName(rs.getString("name")); code.setIndate(rs.getString("indate")); return code; } else { return null; } } catch (Exception e) { throw new RuntimeException(e); }finally { //关闭资源,倒关 try { if(rs != null) rs.close(); if(pstmt != null) pstmt.close(); if(con != null) con.close(); //必须要关 } catch (Exception e) { } } } }