JDBC的使用

JDBC

JDBC编程六步
  1. 注册驱动

    (通知java程序我们即将要连接的是哪个品牌的数据库)

  2. 获取数据库连接

    (java进程和mysql进程,两个进程之间的通道开启了)

  3. 获取数据库操作对象

    这个对象很重要,用这个对象执行sql

  4. 执行sql语句

    执行CRUD操作

  5. 处理查询结果集

    如果第四步是select,才有第五步

  6. 释放资源

    关闭所有的资源(因为JDBC毕竟是进程之间的通信,占用很多的资源,需要关闭!)

    JDBC查询数据
import java.sql.*;
public class Testjdbc {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //配置信息
        //解决中文乱码:useUnicode=true&characterEncoding=utf-8
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String username = "root";
        String password = "123456";
        //加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //链接数据库
        Connection connection = DriverManager.getConnection(url, username, password);
        //向数据库发送SQL的对象Statement(不安全),(安全)PreparedStatement(参Testjdbc2):CRUD
        Statement statement = connection.createStatement();
        //PreparedStatement preparedStatement = connection.prepareStatement();
        //编写SQL
        String sql = "select * from users";
        /*
         * String sql="delete from users where id=4";
         * //受影响的行数,增删改都是用executeUpdate;
         * int i=statement.executeUpdate(sql);
         * */
        //执行查询SQL,返回一个ResultSet :结果集
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()) {
            System.out.println("id=" + resultSet.getObject("id"));
            System.out.println("name=" + resultSet.getObject("name"));
            System.out.println("password=" + resultSet.getObject("password"));
            System.out.println("email=" + resultSet.getObject("email"));
            System.out.println("birthday=" + resultSet.getObject("birthday"));

        }
        //关闭链接,释放资源(必须做)先开后关
        resultSet.close();
        statement.close();
        connection.close();
    }


}
JDBC插入数据
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class Testjdbc2 {
    public static void main(String[] args) throws Exception {
        //配置信息
        //解决中文乱码:useUnicode=true&characterEncoding=utf-8
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        //加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //链接数据库
        Connection connection = DriverManager.getConnection(url, username, password);


        //编写SQL
        String sql = "insert into users(id, name, password, email, birthday) value (?,?,?,?,?)";
        //预编译
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, 6);
        preparedStatement.setString(2, "fu");
        preparedStatement.setString(3, "123456");
        preparedStatement.setString(4, "1117 @qq.com");
        preparedStatement.setDate(5, new Date(new java.util.Date().getTime()));
        //执行SQL
        int i = preparedStatement.executeUpdate();
        if (i > 0) {
            System.out.println("插入成功");
        }
        //关闭链接,释放资源(必须做)先开后关
        preparedStatement.close();
        connection.close();
    }
}
JDBC中的事务
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Testjdbc3 {
    @Test
    public void test() {
        //配置信息
        //解决中文乱码:useUnicode=true&characterEncoding=utf-8
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";
        Connection connection = null;
        //加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //链接数据库
            connection = DriverManager.getConnection(url, username, password);
            //通知数据库开启事务,false开启
            connection.setAutoCommit(false);
            String sql = "update account set money=money-100 where name='A'";
            connection.prepareStatement(sql).executeUpdate();
            //制造错误
            // int i = 1 / 0;
            String sql2 = "update account set money=money+100 where name='B'";
            connection.prepareStatement(sql2).executeUpdate();
            connection.commit();//以上两条SQL都执行成功就提交事务
            System.out.println("success");
        } catch (Exception e) {
            try {
                //如果出现异常,就通知数据库回滚事务
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
读取配置文件连接数据库
  • 在src目录下的resources资源目录下新建一个 db.properties文件
  • 文件下面添加以下内容
#mysql配置文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false
username=root
password=123456
  • 使用该配置文件
public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //资源绑定器
        ResourceBundle bundle=ResourceBundle.getBundle("db");
        //通过属性配置文件拿到信息
        String driver=bundle.getString("driver");
        String url=bundle.getString("url");
        String username=bundle.getString("username");
        String password=bundle.getString("password");

        //加载驱动
        Class.forName(driver);
        //链接数据库
        Connection connection = DriverManager.getConnection(url, username, password);
        //向数据库发送SQL的对象Statement(不安全),(安全)PreparedStatement(参Testjdbc2):CRUD
        Statement statement = connection.createStatement();
        //PreparedStatement preparedStatement = connection.prepareStatement();
        //编写SQL
        String sql = "select * from users";
        /*
         * String sql="delete from users where id=4";
         * //受影响的行数,增删改都是用executeUpdate;
         * int i=statement.executeUpdate(sql);
         * */
        //执行查询SQL,返回一个ResultSet :结果集
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()) {
            System.out.println("id=" + resultSet.getObject("id"));
            System.out.println("name=" + resultSet.getObject("name"));
            System.out.println("password=" + resultSet.getObject("password"));
            System.out.println("email=" + resultSet.getObject("email"));
            System.out.println("birthday=" + resultSet.getObject("birthday"));

        }
        //关闭链接,释放资源(必须做)先开后关
        resultSet.close();
        statement.close();
        connection.close();
    }
SQL注入

在模拟用户登录中

如果采用的是Statement对象执行sql

查询用户名和密码是否正确的sql语句为:

sql= "select * from where name='"+输入的密码+"' and password = '"+输入的用户名+"'";

输入用户名:任意值

输入密码 :任意值 ’ or ‘1’=‘1’

当输入上面的用户名和密码时:

sql=select * from where name='任意值' and password ='任意值' or '1'='1';

我们可以看出sql语句的含义发生了变化,1=1恒成立,所以该语句执行会返回所有的用户信息。

这就是sql注入。

sql注入的根本原因是:先进行了字符串的拼接,然后再进行的编译
怎么避免sql注入
  • java,sql.Statement接口的特点:先进行字符串的拼接,然后再进行编译

    优点:使用Statement可以进行sql语句的拼接

    缺点:因为拼接的存在,导致可能给不法分子机会。导致sql注入。

  • java.sql.PreparedStatement接口的特点:先进行sql语句的编译,然后再进行sql语句的传值。

    优点:避免sql注入

    缺点:没有办法进行sql语句的拼接,只能给sql语句传值。

    PreparedStatement预编译的数据库操作对象

Statement是PreparedStatement的父类

采用PreparedStatement对象

sql ="select * from t_user where login_name =? and login_ped = ?"

这里sql语句里面的?表示占位符,?只能传值,不能进行sql语句拼接。

PreparedStatement的具体使用参考:

PreparedStatement的具体使用参考目录JDBC插入数据

Statement的使用场景

当我们浏览一组数据时(例如显示学生成绩信息),我们可以选择将该组数据升序显示或者降序输出。这时我们就可以采用Statement并选择注入desc降序或者注入asc升序排序。

使用PreparedStatement模糊查询
sql = "select ename from emp where ename like %?%";//该写法错误
sql = “select ename from emp where ename like ?";//正确写法
PreparedStatement ps=conn。prepareStatement(sql);
ps.setString(1,"%S%");
JDBC封装
import java.sql.*;
import java.util.ResourceBundle;

/**
 * 数据库工具类,便于JDBC的代码编写
 */
public class DBUtil {
    private DBUtil(){

    }

    //类加载时绑定属性资源文件
    private static ResourceBundle bundle=ResourceBundle.getBundle("db");
    //注册驱动
    static {
        try {
            Class.forName(bundle.getString("driver"));
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接对象
     * @return 新的连接对象
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        String url=bundle.getString("url");
        String user=bundle.getString("user");
        String password=bundle.getString("password");
        Connection conn= DriverManager.getConnection(url, user, password);
        return conn;
    }

    /**
     * 释放资源
     * @param conn 连接对象
     * @param statement 数据库操作对象
     * @param rs 查询结果集
     */
    public static void release(Connection conn, Statement statement,ResultSet rs){
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
关于DDL语句的悲观锁

对于一个DQL语句来说,末尾是可以添加这样一个关键字:for update

select ename,sal from emp where job ='MANAGER' for update;

以上sql语句的含义是:

在本次事务的执行过程当中,job='MANAGER’的记录被查询,这些记录在我查询的过程中,任何人任何事务都不能对这些记录进行修改操作,直到我当前事务结束。

这种机制被称为:行级锁机制(又叫做悲观锁!)

在mysql中是这样的:
当使用select …where …for update …时,

mysql进行row lock还是table lock只取决于是否能使用索引(例如主键,unique字段),

能则为行锁,否则为表锁:未查到数据则无锁。而使用’<>','like’等操作时,索引会失效,自然进行的是able lock。

所以慎用 for update。

整个表锁住会导致性能降低。

使用for update的时候,最好是锁主键,或者具有unique约束的字段,锁别的字段可能会导致整个表锁住。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值