jdbc访问数据库步骤
1、Class.forName()加载驱动
2、DriverManager获取Connection连接
3、创建Statement执行SQL语句
4、返回ResultSet查询结果
5、释放资源
public class DBUtils { public static Connection getCon() { Connection con = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); String url = "jdbc:oracle:thin:@127.0.0.1:1521:xe"; String user = "root"; String password = "123456"; con = DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return con; } public static void close(ResultSet rs,Statement st ,Connection con) { if (rs != null) { try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (st != null) { try { st.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Connection con = DBUtils.getCon(); Statement st = con.createStatement(); //Statement会有sql注入风险 String sql = "select * from t_user where usname= '" + usname + "' and psword ='" + psword + "'"; System.out.println("sql:"+sql); ResultSet rs = st.executeQuery(sql); if(rs.next()) { System.out.println("登录成功!"); System.out.println(rs.getInt(1)); System.out.println(rs.getString(2)); System.out.println(rs.getString(3)); System.out.println(rs.getInt(4)); System.out.println(rs.getString(5)); }else { System.out.println("用户名或密码不正确,请重新输入!"); }
Connection接口常用方法
Statement接口
Statement 是 Java 执行数据库操作的一个重要接口,用于在已经建立数据库连接的基础上,向数据库发送要执行的SQL语句。Statement对象,用于执行不带参数的简单SQL语句。
ResultSet
数据查询操作会利用SQL语句向数据库发出SELECT查询指令,而查询的结果如果要返回给程序进行处理,就必须通过ResultSet接口来进行封装,ResultSet是一种可以保存任意查询结果的集合结构,所有查询结果会通过ResultSet在内存中形成一张虚拟表的形式,而后开发者可以根据数据行的索引,依照数据类型获取列数据内容
PreparedStatement
继承自statement
preparedStatement防止sql注入的方式是把用户非法输入的字符用\反斜杠做了转义,从而达到了防止sql注入的目的
public class Controller1 { public static void main(String[] args) throws Exception { //1.PreparedStatement和Statement啥关系? //2.为啥要用这个玩意儿?2.1防止SQL注入2.2预编译能提升效率 System.out.println("请输入用户名:"); Scanner sc = new Scanner(System.in); String usname = sc.nextLine(); System.out.println("请输入密码:"); String psword = sc.nextLine(); Connection con = DBUtils.getCon(); String sql = "select * from t_user where username= ? and password =?"; PreparedStatement pst = con.prepareStatement(sql); pst.setString(1, usname); pst.setString(2, psword); ResultSet rs = pst.executeQuery(); if(rs.next()) { System.out.println("登录成功!"); System.out.println(rs.getInt(1)); System.out.println(rs.getString(2)); System.out.println(rs.getString(3)); System.out.println(rs.getInt(4)); System.out.println(rs.getString(5)); }else { System.out.println("用户名或密码不正确,请重新输入!"); } DBUtils.close(rs, pst, con); } }