我爱编程

Java Web学习笔记之Jdbc

2018-04-06  本文已影响34人  EclipseO2

1. 概念

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

2. 流程

2.1. 得到 Connector 对象
2.2. 具体过程

jdbc.properties

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

各种参数的含义

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;
}

代码分析

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

3.1 增、删、改

  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();
            }   
        }
    }
  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 查

  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);
    }
}

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

@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);
    }
}
上一篇下一篇

猜你喜欢

热点阅读