GithubHelp home page GithubHelp logo

collegestudy's People

Stargazers

曾志杰 avatar  avatar

Watchers

 avatar

collegestudy's Issues

JDBC: 解决sql注入 实现事务回滚

源码赋与JDBC文件
package com.bjpowernode.jdbc;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**

  • 实现JDBC,用户登录系统
    */
    public class JDBCText01 {
    public static void main(String[] args) {
    //初始化界面
    Map<String,String> userLoginInfo = initUI();
    //验证用户名和密码
    Boolean result = Login(userLoginInfo);
    System.out.println(result ? "登录成功" : "登录失败");

    }

    /**

    • 验证用户名和密码

    • @param userLoginInfo 用户名和密码

    • @return true成功 false失败
      */
      private static boolean Login(Map<String, String> userLoginInfo) {
      //初始化
      Boolean result = false;
      Connection conn = null;
      Statement stmt = null;
      ResultSet rs = null;

      String LoginName = userLoginInfo.get("LoginName");
      String LoginPwd = userLoginInfo.get("LoginPwd");

      try {
      //1.注册驱动
      Class.forName("com.mysql.cj.jdbc.Driver");
      //2.获取链接
      conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentsdb","root","root");
      //3.获取数据库操作对象
      stmt = conn.createStatement();
      //4.执行sql
      String sql = "select * from t_user where Sname = '"+LoginName+"' and Spwd = '"+LoginPwd+"' ";

       rs = stmt.executeQuery(sql);
       //5.处理结果集
       if(rs.next()){
           result = true;
      

// System.out.println(rs.getString("Sname"));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//6.释放资源
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

    return result;
}

/**
 * 实现界面初始化
 * @return 用户用户名和密码
 */
private static Map<String, String> initUI() {

    Scanner scanner = new Scanner(System.in);

    System.out.println("用户名");
    String LoginName = scanner.nextLine();

    System.out.println("密码");
    String LoginPwd = scanner.nextLine();

    Map<String,String> userLoginInfo = new HashMap<>();
    userLoginInfo.put("LoginName",LoginName);
    userLoginInfo.put("LoginPwd",LoginPwd);

    return userLoginInfo;
}

}

package com.bjpowernode.jdbc;

import java.sql.*;

/**

  • JDBC, MySQL更改实现数据同步
    */
    public class JDBCText02 {
    public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
    //1.注册驱动
    Class.forName("com.mysql.cj.jdbc.Driver");
    //2.获取链接
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentsdb","root","root");
    //3.获取数据库操作对象
    stmt = conn.createStatement();
    //4.执行sql
    String sql = "INSERT INTO t_user(Sno,Sname,Spwd) VALUES ('010','chenyi','123')";
    System.out.println(stmt.executeUpdate(sql)==1?"插入成功":"插入失败");
    } catch (Exception e) {
    e.printStackTrace();
    }finally {
    if(conn != null){
    try {
    conn.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    if(stmt != null){
    try {
    stmt.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    if(rs != null){
    try {
    rs.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    }
    }
    }

package com.bjpowernode.jdbc;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**

  • 使用预编译preparedStatement对象
  • ? 占位符
  • PreparedStatement.setString()对占位符赋值
  • 解决sql注入
    */
    public class JDBCText03 {
    public static void main(String[] args) {
    //初始化界面
    Map<String,String> userLoginInfo = initUI();
    //验证用户名和密码
    Boolean result = Login(userLoginInfo);
    System.out.println(result ? "登录成功" : "登录失败");
}

/**
 * 验证用户名和密码
 * @param userLoginInfo 用户名和密码
 * @return true成功  false失败
 */
private static boolean Login(Map<String, String> userLoginInfo) {
    //初始化
    Boolean result = false;
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    PreparedStatement ps = null;  //预编译的数据库操作对象

    String LoginName = userLoginInfo.get("LoginName");
    String LoginPwd = userLoginInfo.get("LoginPwd");

    try {
        //1.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取链接
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentsdb","root","root");
        //3.获取数据库操作对象
        //  ?为占位符
        String sql = "select * from t_user where Sname = ? and  Spwd =  ?";
        //  发送sql语句给DBMS,然后对sql语句进行预先编译
        ps = conn.prepareStatement(sql);
        ps.setString(1,LoginName);
        ps.setString(2,LoginPwd);
        //4.执行sql语句
        rs = ps.executeQuery();
        //5.处理结果集
        if(rs.next()){
            result = true;

        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        //6.释放资源
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stmt != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    return result;
}

/**
 * 实现界面初始化
 * @return 用户用户名和密码
 */
private static Map<String, String> initUI() {

    Scanner scanner = new Scanner(System.in);

    System.out.println("用户名");
    String LoginName = scanner.nextLine();

    System.out.println("密码");
    String LoginPwd = scanner.nextLine();

    Map<String,String> userLoginInfo = new HashMap<>();
    userLoginInfo.put("LoginName",LoginName);
    userLoginInfo.put("LoginPwd",LoginPwd);

    return userLoginInfo;
}

}

package com.bjpowernode.jdbc;

import java.sql.*;

/**

  • 使用 conn.setAutoCommit(false);关闭自动提交,开启事务
  •  成功 conn.Commit();手动提交
    
  •  失败 conn.rollback();回滚
    
  • 完成事务

*/
public class JDBCText04 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;

    try {
        //注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取连接
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentsdb",
                "root","root");
        //将自动提交关闭
        conn.setAutoCommit(false);
        //3.获取预编译sql操作对象
        String sql = "update t_user set Sname = ? where Sno = ?";
        ps = conn.prepareStatement(sql);
        //事件1
        ps.setString(1,"zzj");
        ps.setString(2,"004");
        int count = ps.executeUpdate();
        //事件2
        ps.setString(1,"ppp");
        ps.setString(2,"005");
        count += ps.executeUpdate();

        System.out.println( count==2 ? "修改成功":"修改失败");
        //手动提交
        conn.commit();
    } catch (Exception e) {
        //事务回滚
        if(conn!=null){
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
        e.printStackTrace();
    }finally {
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(ps!=null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


    }
}

}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.