- 连接数据库
1 public class DbConnection { 2 3 public Connection getDbConnection() { 4 //声明一个连接类Connection类,它的实例对象用来保存和数据库的连接 5 Connection con = null; 6 //定义驱动程序字符串(厂商提供,固定的) 7 String DriverName = "oracle.jdbc.driver.OracleDriver"; 8 //数据库的url,用户名和密码 9 String url = "jdbc:oracle:thin:@localhost:1521:orcl"; 10 String usr = "system"; 11 String pwd = "123456"; 12 13 //1、加载jdbc驱动 ??Class.forName()这个知识点还没看(time:2020.12.2) 14 try { 15 Class.forName(DriverName); 16 } catch (ClassNotFoundException e) { 17 e.printStackTrace(); 18 } 19 20 //2、建立连接 21 //驱动程序管理器调用驱动程序对象与指定的数据库建立连接 22 try { 23 con = DriverManager.getConnection(url,usr,pwd); 24 } catch (SQLException e) { 25 e.printStackTrace(); 26 } 27 28 //返回连接对象 29 return con; 30 } 31 32 }
2.如何执行sql语句,以查询语句为例
1 public class UserVoDaoImpl implements UserVoDao { 2 private Connection con; 3 4 public UserVoDaoImpl() { 5 con = new DbConnection().getDbConnection(); 6 } 7 8 // 从数据库查询用户 9 public boolean findUserVo(UserVo vaule) { 10 boolean flag = false; 11 ResultSet set =null; 12 13 // 1、定义预加载类PreparedStatement 14 PreparedStatement pstmt = null; 15 16 // 2、定义sql语句 17 String sql = "seclet * from user_table where id=? pwd=? type=?"; 18 19 // 3、预加载sql 20 try { 21 pstmt = con.prepareStatement(sql); 22 } catch (SQLException e1) { 23 e1.printStackTrace(); 24 } 25 26 // 4、用封装好信息的对象,传参给占位符 27 try { 28 //下面这段还可以再封装一下 29 pstmt.setString(1, vaule.getId()); 30 pstmt.setString(2, vaule.getPwd()); 31 pstmt.setString(3, vaule.getType()); 32 } catch (SQLException e2) { 33 e2.printStackTrace(); 34 } 35 36 // 5、执行完整的sql句 37 try { 38 //用ResultSet对象装查询到的结果,要是没有查询到,set.next() =false 39 set= pstmt.executeQuery(); 40 if(set.next()) { 41 flag = true; 42 } 43 } catch (SQLException e) { 44 e.printStackTrace(); 45 } 46 return flag; 47 } 48 49 }