Java Web学习笔记之Jdbc

1. 概念

Jdbc (java database connectivity):Java数据库连接,就是用Java语言来操作数据库。原来我们操作数据库是在控制台中通过sql语句来操作数据库,而Jdbc是用Java语言来向数据库发送sql语句来操作数据库。

2. 流程

2.1. 得到 Connector 对象
  • 导入 jar 包:mysql-connector-java-5.1.42-bin.jar
  • 导入 jdbc.properties 的配置文件
  • 从配置文件中读入 urljdbcUrluserpassword 参数
  • 加载驱动类:Class.forName("类名");
  • 使用 DriverManager 类来得到 Connection 对象。
2.2. 具体过程

jdbc.properties

driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/test
user=root
password=123456

各种参数的含义

  • driver:数据库的驱动类,我使用的是 mysql, 所以使用 com.mysql.jdbc.Driver 这个类
  • jdbcUrl:这里我使用的是 mysql 的通用格式,jdbc:mysql://localhost:3306/数据库名称
  • user:数据库的用户名
  • password:数据库的密码

Demo

public static Connection getConnection() throws Exception {
        // 1. 准备连接数据库的 4 个字符串.
        String driverClass = null;
        String jdbcUrl = null;
        String user = null;
        String password = null;

        // 获取 jdbc.properties 的输入流
        InputStream in = JDBCTools.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        properties.load(in);

        driverClass = properties.getProperty("driver");
        jdbcUrl = properties.getProperty("jdbcUrl");
        user = properties.getProperty("user");
        password = properties.getProperty("password");

        // 2. 加载数据库驱动程序
        Class.forName(driverClass);

        // 3. 通过 DriverManger 的 getConnection 方法获取数据库连接.
        Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
        return connection;
}

代码分析

  • 这里我是通过数据流的方式,先准备好 jdbc.properties 这一数据库配置文件,然后通过输入流的方式,获取配置信息中的键对应的值,最后进行数据库的连接
  • 当然,也可以直接在方法里面输入配置信息,不过为了寻求低耦合,这种方法最适合

3. 对数据库进行增、删、改、查

3.1 增、删、改

  • 使用 Statement
  1. Statement:用于执行 SQL 语句的对象
    1). 通过 Connection 的 createStatement() 方法来获取
    2). 通过 executeUpdate(sql) 可以执行 SQL 语句
    3). 传入的 SQL 可以是 Insert、Update 或者 Delete,但不能是 Select

  2. Connection、Statement 都是应用程序和数据库服务器的连接资源,使用后一定要关闭,需要在 finally 中关闭 Connection 和 Statement 对象

  3. 关闭的顺序:先关闭后获取的,即先关闭 Statement 后关闭 Connection

@Test
public void testStatement() throws Exception{
    //1. 获取数据库连接
    Connection connection = null;
    Statement statement = null;
        
    try {
        connection = getConnection2();
            
        //3.进行 SQL 语句的 增删改查 操作
        String sql = null;
            
        //插入
//      sql = "INSERT INTO customers (NAME, EMAIL, BIRTH) VALUES ('luwenhe', 'luwenhe12345@126.com', '1996-1-13')";
        //删除
//      sql = "DELETE FROM customers WHERE id = 1";
        //修改
        sql = "UPDATE customers SET name = 'TOM' WHERE id =2";
            
        //4. 执行插入
        //1). 获取操作 SQL 语句的 Statement 对象: 
        //    调用 Connection 的 createStatement() 方法来获取
        statement = connection.createStatement();
        
        //2). 调用 Statement 对象的 executeUpdate(sql) 执行 SQL 语句进行插入
        statement.executeUpdate(sql);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                //5. 关闭 Statement 对象
               if(statement != null)    //如关闭 statement 时有异常, 则关闭 connection
                    statement.close();
               } catch (Exception e) {
                    e.printStackTrace();
               } finally {
                //2. 关闭连接
                   if(connection != null)
                       connection.close();
            }   
        }
    }


  • 使用 PreparedStatement
  1. PreparedStatement 是 Statement 的子接口,可以传入带占位符的 SQL,并且提供了补充占位符变量的方法
    1). 创建 PreparedStatement:PreparedStatement ps = connection.preparedStatement(sql)
    2). 调用 PreparedStatement 的 setXxx(int index, Object val) 设置占位符,index 从 1 开始
    3). 执行 SQL 语句的 excuteQuery() 或者 executeUpdate(). 注意:执行时不需要传入 SQL 语句
@Test
public void testPreparedStatement() {
    Connection connection = null;
    PreparedStatement preparedStatement = null;

    try {
        connection = JDBCTools.getConnection();

        String sql = "INSERT INTO customers(name, email, birth) VALUES(?,?,?)";
        preparedStatement = connection.prepareStatement(sql);
        // 设置 SQL 语句
        preparedStatement.setString(1, "luwenh");
        preparedStatement.setString(2, "luwenh@163.com");
        preparedStatement.setDate(3, new Date(new java.util.Date().getTime()));

        preparedStatement.executeUpdate();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        JDBCTools.release(connection, preparedStatement, null);
    }
}


3.1 查

  • 使用 ResultSet:结果集,封装了使用 JDBC 进行查询的结果
  1. 调用 Statement 对象的 executeQuery(sql) 可以得到结果集
  2. ResultSet 返回的实际上就是一张数据表,有一个指针指向数据表的第一行的前面,可以调用 next() 方法检测下一行是否有效,若有效则返回 true,且指针下移
  3. 当指针对位到一行时,可以通过调用 getXxx(index) 或者 getXxx(columnName) 获取每一列的值,例如:getInt(1)、getString("birth")
  4. ResultSet 也需要关闭
@Test
public void testResultSet(){
    /**
    * 获得 id=4 的 customers 数据表的信息记录, 并打印
     */
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;
        
    try {
        //1. 获取 Connection
        connection = JDBCTools.getConnection();
        System.out.println(connection);
            
        //2. 获取 Statement
        statement = connection.createStatement();
            
        //3. 准备 SQL
        String sql = "SELECT id, name, email, birth FROM customers";
            
        //4. 执行查询, 得到 ResultSet
        resultSet = statement.executeQuery(sql);        //结果集
            
        //5. 处理 ResultSet
        while(resultSet.next()){
            int id = resultSet.getInt(1);
            String name = resultSet.getString(2);
            String email = resultSet.getString(3);
            Date birth = resultSet.getDate(4);
        }
            
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //6. 关闭数据库资源 
        JDBCTools.release(resultSet, statement, connection);
    }
}


  • ResultSet 的原理图解


    ResultSet 原理图解

4. 获取数据库自动生成的主键

  • 通过 PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) 这一方法来生成 PreparedStatement 对象
  • 在结果集中只有一列 FENERATED_KEY,用于存放主键值
    注意:此方法只能获取数据库中自增的主键值
@Test
public void testGetKeyValue() throws SQLException {
        
    Connection connection = null;
    PreparedStatement preparedStatement = null;
        
    try {
        connection = JDBCTools.getConnection();
        String sql = "INSERT INTO customers(name, email, birth) VALUES(?,?,?)";
            
        //使用重载的 preparedStatement(sql, flag) 来生成 PreparedStatement 对象
        preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            
        preparedStatement.setString(1, "ABC");
        preparedStatement.setString(2, "luwenhe@126.com");
        preparedStatement.setDate(3, new Date(new java.util.Date().getTime()));
            
        preparedStatement.executeUpdate();
            
        //通过 getGeneratedKeys() 获取包含了新生成的主键的 ResultSet 对象
        //在 ResultSet 中只有一列 GENERATED_KEY, 用于存放新生成的主键值
        ResultSet rs = preparedStatement.getGeneratedKeys();
        if(rs.next()){
            System.out.println(rs.getString(1));
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        JDBCTools.release(connection, preparedStatement, null);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,542评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,822评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,912评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,449评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,500评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,370评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,193评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,074评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,505评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,722评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,841评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,569评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,168评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,783评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,918评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,962评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,781评论 2 354