Android03-JDBC

1.jdbc的概念
1:JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。是Java访问数据库的标准规范。
2:JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。
3:JDBC需要连接驱动,驱动是两个设备要进行通信,满足一定通信数据格式,数据格式由设备提供商规定,设备提供商为设备提供驱动软件,通过软件可以与该设备进行通信。

2.JDBC开发步骤

1:注册驱动。
2:获得连接。
3:获得语句执行平台。
4:执行sql语句。
5:处理结果。
6:释放资源。

3.java执行SQL的实现

public static void run1() throws Exception {
    //1.注册驱动
    // java.sql.DriverManager.registerDriver(Driver driver)
    //由于com.mysql.jdbc.Driver类的静态代码块进行了注册
    //所以我们只需要将com.mysql.jdbc.Driver加入JVM中,就可以了
    Class.forName("com.mysql.jdbc.Driver");

    //2.获取数据库的连接
    //static Connection getConnection(String url, String user, String password)
    //url,数据库的连接地址jdbc:mysql://连接主机的IP地址:端口号/数据库名
    String url = "jdbc:mysql://localhost:3306/my1";
    String username = "root";
    String password = "123456";
    Connection connection = DriverManager.getConnection(url, username, password);

    //3.获取语句的执行平台 获取SQL语句的执行对象
    //Statement createStatement()
    //Statement 可以将SQL语句发送到数据库
    Statement statement = connection.createStatement();

    //4 通过执行者对象,执行SQL语句,并返回SQL的结果
    //int executeUpdate(String sql),执行insert,update,delete语句
    int i = statement.executeUpdate("" +
            "INSERT INTO sort(sname,sprice,sdesc) VALUES('家电来了',1000,'优惠的促销')");
    System.out.println(i);

    statement.close();
    connection.close();
}

4.查询的实现

public static void run3() throws Exception{
    Statement statement = run2();
    String sql = "select * from sort";

    //获取查询的处理对象
    ResultSet resultSet = statement.executeQuery(sql);

    //ResultSet的原理和Iterator一样,所以使用while循环获取
    while (resultSet.next()){
        //String getString(String columnLabel) 
        //通过类名获取数据库中指定列的值 
        String s = resultSet.getString("sid");
        System.out.println(s);
    }
}

5.SQL攻击

SELECT * FROM users1 WHERE username='add' AND PASSWORD=222 OR 1=1;or是两边有一边为true,结果就是true,所以这是不管username和password是什么数据,都会查询到结果。
//SQL攻击的代码体现,不管username和password是什么数据,都会查询到结果。
public static void run4() throws Exception {
    Statement statement = run2();
    String sql = "SELECT * FROM users1 WHERE username='add' AND PASSWORD=222 OR 1=1";

    ResultSet resultSet = statement.executeQuery(sql);

    while (resultSet.next()){
        System.out.println(resultSet.getString("username"));
    }
}
//键盘输入时的SQL攻击
//现在不管username和password是什么数据,只要在password后面加上'or'1=1或者' or '1‘=’1,都会查询到结果。
public static void run5() throws Exception {
    Scanner scanner = new Scanner(System.in);
    String username = scanner.nextLine();
    String password = scanner.nextLine();

    Statement statement = run2();
    String sql = "SELECT * FROM users1 WHERE username='"+username+"' AND PASSWORD='"+password+"'";

    System.out.println(sql);

    ResultSet resultSet = statement.executeQuery(sql);

    while (resultSet.next()){
        System.out.println(resultSet.getString("username"));
    }
}

6.防止SQL攻击,使用预编译PrepareStatement

1:SQL预编译存储,多次高效的执行。
2:防止SQL注入攻击。
3:使用Connection的 PreparedStatement prepareStatement(String sql)方法获取,PrepareStatement对象。
//PreparedStatement查询的使用
public static void run6() throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    String url = "jdbc:mysql://localhost:3306/my1";
    String username = "root";
    String password = "123456";
    Connection connection = DriverManager.getConnection(url, username, password);

    //使用? 作为占位符
    String sql = "SELECT * FROM users1 WHERE username=? AND PASSWORD=?";

    //获取PreparedStatement预编译接口
    PreparedStatement preparedStatement = connection.prepareStatement(sql);

    //设置占位符的值
    preparedStatement.setObject(1,"a");
    preparedStatement.setObject(2,"1");

    //insert、update、delete使用preparedStatement.executeUpdate();
    ResultSet resultSet = preparedStatement.executeQuery();

    while (resultSet.next()){
        System.out.println(resultSet.getString("id"));
    }

    resultSet.close();
    preparedStatement.close();
    connection.close();
}

7.JDBCUtils

public class JDBCUtils {

    private JDBCUtils(){}
    private static final Connection connection;

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/my1";
            String username = "root";
            String password = "123456";
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception se){
            throw new RuntimeException("数据库连接获取失败");
        }
    }

    public static Connection getConnection(){
        return connection;
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if (resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

8.配置文件和ClassLoader加载的JDBCUtils

public class JDBCUtils {

    private JDBCUtils(){}
    private static Connection connection;
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;

    static {
        try {
            readResources();
            Class.forName(driverClass);
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception se){
            System.out.println(se);
            throw new RuntimeException("数据库连接获取失败");
        }
    }

    private static void readResources() throws IOException {
        //当项目发布时,没有resources文件夹
        //所以不能使用new FileInputStream("resources\\database.properties");加载配置文件
        //而应该获取来的加载器,此时类的加载器的目录是class字节码文件的目录
        //所以类的加载器可以从字节码根目录进行加载
        Class<Test1> test1Class = Test1.class;
        //获取类的加载器
        ClassLoader classLoader = test1Class.getClassLoader();
        //类的加载器从字节码的根目录加载文件
        InputStream inputStream = classLoader.getResourceAsStream("database.properties");

        Properties properties = new Properties();
        properties.load(inputStream);

        driverClass = properties.getProperty("driverClass");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
    }

    public static Connection getConnection(){
        return connection;
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if (resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

9.使用ResourceBundle加载数据库配置信息

private static String driverClassName;
private static String url;
private static String username;
private static String password;

static {
    ResourceBundle resourceBundle = ResourceBundle.getBundle("database");

    driverClassName = resourceBundle.getString("driverClass");
    url = resourceBundle.getString("url");
    username = resourceBundle.getString("username");
    password = resourceBundle.getString("password");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值