赞
踩
我们之前操作数据库--都是通过图形化界面来对mysql进行操作,我们实际开发是我们应该通过java代码来完成对数据库的操作
Java :OOP 面向对象的编程对象
SQL: 结构化查询语言
思考: java和sql是两种不同的编程语言。连接必须请翻译。翻译程序---每个数据库厂商都提高了翻译软件-- -打包jar。---我们的java代码引入jar就可完成与数据库的沟通。网上可以下载。
代码(增删改)
- // 1、加载驱动
- Class.forName("com.mysql.cj.jdbc.Driver");
- // 2、获取连接数据库
- String url = "jdbc:mysql://localhost:3306/数据库名"
- String user = "root";
- String psw = "root";
- Connection con = DriverManager.getConnection(url,user,psw);
- //3. 获取执行sql语句的对象
- Statement st = con.createStatement();
- //4. 执行sql语句: 执行增删改的sql
- String sql = "sql语句";
- st.executeUpdate(sql);
- st.close();
- con.close();
代码(查)
- public static void q(){
- Connection conn = null;
- Statement stmt = null;
- ResultSet rs = null;
-
- try {
- Class.forName("com.mysql.cj.jdbc.Driver");
- conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
- "root", "root");
- stmt = conn.createStatement();
- String sql = "select * from dept";
- rs = stmt.executeQuery(sql);
- System.out.println("编号\t部门\t\t地址");
- while (rs.next()){
- int deptNo = rs.getInt(1);
- String dName = rs.getString(2);
- String loc = rs.getString(3);
- System.out.println(deptNo +"\t"+ dName +"\t"+loc);
- }
- } catch (Exception e) {
- System.out.println(e.getMessage());;
- }finally {
- try {
- if (rs != null) {
- rs.close();
- }
- if (stmt != null) {
- stmt.close();
- }
- if (conn != null) {
- conn.close();
- }
- } catch (SQLException e) {
- System.out.println(e.getMessage());;
- }
-
- }

- public static void selectAll() {
- ResultSet rs=null;
- Statement st=null;
- Connection conn=null;
- try {
- Class.forName("com.mysql.cj.jdbc.Driver");
- String url = "jdbc:mysql://localhost:3306/qy174";
- String user = "root";
- String password = "root";
- conn = DriverManager.getConnection(url, user, password);
- st = conn.createStatement();
- String sql = "select * from dept";
- //执行查询的sql语句 ResultSet:把数据库表返回的记录都封装到ResultSet结果集对象中
- rs = st.executeQuery(sql);
- //遍历结果集 next():判断下一条是否有记录,如果有记录返回true并且指针下移。
- while (rs.next()) {
- //获取当前行的指定列的值
- int deptno = rs.getInt("deptno");
- String dname = rs.getString("dname");
- String loc = rs.getString("loc");
- System.out.println("部门编号:" + deptno +
- ";部门名称:" + dname + ";部门地址:" + loc);
- }
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException throwables) {
- throwables.printStackTrace();
- } finally {
- if(rs!=null){
- try {
- rs.close();
- } catch (SQLException throwables) {
- throwables.printStackTrace();
- }
- }
- if(st!=null){
- try {
- st.close();
- } catch (SQLException throwables) {
- throwables.printStackTrace();
- }
- }
- if(conn!=null){
- try {
- conn.close();
- } catch (SQLException throwables) {
- throwables.printStackTrace();
- }
- }
- }
-
- }

我们输入的账号和密码再数据库中压根不存在,但是显示登录成功。出现了sql注入安全隐患问题。 由于Statement类的问题。找到PreparedStatement它是Statement的子类
出现这类问题的主要原因是系统没有对用户输入的内容进行充分的检查,而用户输入的数据中存在非法的 sql 语句导致绕过了验证,从而去恶意的去攻击数据库。
为了避免这类问题:在获取执行sql语句的对象的时候:使用 PreparedStatement
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。