PreparedStatement implements operations on database tables

Note: The links below are all based on mysql as an example, @Test is a Junit4 comment for testing, and the tool classes used are described in the previous section

  1. Post the table-building statement first for easy follow-up
CREATE TABLE `fruit` (
  `fruitName` varchar(10) COLLATE utf8_bin DEFAULT NULL COMMENT 'Fruit Name',
  `id` int(11) NOT NULL COMMENT 'id',
  `price` double DEFAULT NULL COMMENT 'Fruit price',
  `info` varchar(20) COLLATE utf8_bin DEFAULT NULL COMMENT 'introduce',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

2. Insert several pieces of data for later use

insert  into `fruit`(`fruitName`,`id`,`price`,`info`) values 
('Pear',2,14,'Pears are delicious'),
('Banana',3,11,'Bananas are also delicious'),
('pineapple',4,13,'Pineapples are delicious!');

First get the connection call the getConncetion method in the tool class JdbcUtils mentioned earlier get the connection conn, write the sql statement, then call the prepareStatement of Conn to precompile the sql statement. The code is as follows

        //Get Database Links
        Connection  connection = JdbcUtils.getConnection();
        //Define the sql statement to execute
        String sql="update fruit set fruitName=? where id=?";
        //Precompiled sql statement
        PreparedStatement ps = connection.prepareStatement(sql);
  1. You may find that sql statements are different. Usually the sql statement we write should be update fruit set fruitName="apple" where id=2, here? It's called a placeholder, which is a place where I'm not sure what to fill. You can give me the space first, and then I can add the data I want when I want to use it, so what should we do?
  2. PreparedStatement has a method for setting content that calls ps.setXxx(intparameterIndex, Object x). The first parameter, intparameterIndex, specifies the first placeholder. Note that this does not start from 0, but from 1. The second parameter depends on the type you want to add. For example, if we want fruitName to be an apple, we can call ps.setString(1,'Apple') setting, which means that he is the first placeholder and Apple is the data you want to add. If you enter an int type, you can call the ps.setInt() method, and so on, you can call different methods depending on the type of data. You can use it in the IDA or eclipse IDE. Get out.

The next step is to execute sql, calling the execute method in PreparedStatement to execute

//Execute sql statement
ps.execute();

PreparedStatement also needs to close when we run out of connections and throws an exception when closing. Just wrap try-catch

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

Of course, if we directly determine if connection and ps are null, we will get an error because of the scope problem. We want to raise the scope to declare Connection and PreredStatement as null above, and to get connections, precompile sql statements and execute sql statements wrapped up in try-catch-final, and put closed connections in final

/**
     * Modify a message
     * @throws Exception
     */
    @Test
    public void test2() throws Exception {
        Connection connection=null;
        java.sql.PreparedStatement ps=null;
        try {
            //Get Database Links
            connection = JdbcUtils.getConnection();
            //Precompiled sql statement
            String sql="update fruit set fruitName=? where id=?";
            ps = connection.prepareStatement(sql);
            //Fill placeholders
            ps.setString(1,"Chestnuts");
            ps.setInt(2,1);
            //implement
            ps.execute();
            System.out.println("One data was modified successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
             //Close Connection
            try {
                if (connection!=null)
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            try {
                if (ps!=null)
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

Considering closing the connection every time, you can encapsulate the closing connection as a method that can be called when needed

    /**
     *  close resource
     * @param con
     * @param ps
     */
    public static void colseResource(Connection con, PreparedStatement ps)  {
        if (con!=null) {
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (ps!=null) {
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

Direct JdbcUtils when used. CloeRecsource() passes in the connection and reparedStatement.

Keywords: Database JDBC

Added by ralph4100 on Wed, 26 Jan 2022 21:23:21 +0200