Examples of basic Java and database operations to achieve jdbc

I. INTRODUCTION

JDBC: jdbc java database connectivity, jdbc java technology platform is a standardized technology (which is a set of API interface)

    API java.sql.*

      Three interfaces
        Connection connection
        Statement Statement execute sql statement
        ResultSet result set execute select statement

      A class
        DriverManager obtain connections to the database

Second, the steps

  1, the driving load, obtain the connection conn

  2. Create a statement

  3, the implementation of the statement (Find executeQuery , add executeUpdate, delete executeUpdate , update executeUpdate )

  4, the process returns to the data (ResultSet- result set, INT- impact number rows)

  5. Close the resource (back to front)

Third, the project built examples

  1, the new Java project (the root of the new lib file, add the ojdbc14.jar Oracle or other database-driven package, remember to build path add into the project)

  2, in the src directory path and a new packet path within the package, the test type

  

Import the java.sql *. ; 

public  class ConnectionTest {
     public  static  void main (String [] args) { 
        String SQL = "SELECT * from EMP" ; 
        Connection Conn = null ; 
        the Statement STM = null ; 
        the ResultSet RS = null ;
         the try {
             / / 1: load drive 
            the Class.forName ( "oracle.jdbc.driver.OracleDriver" );
             // 2. database connection
            DriverManager.getConnection = conn ( "jdbc: the Oracle: Thin: @localhost: 1521: orcl", "scott", "Tiger" ); 

            System.out.println ( "! data connection success" );
             // 3: Creating a statement 
            = STM conn.createStatement (); 

            // . 4: querying a database (add, delete, change (the executeUpdate (SQL))) 
            RS = stm.executeQuery (SQL); 

            // . 5: process data returned by the database (or data collection Effect of the number of rows int)
             // rs.next () is important to 
            the while (rs.next ()) { 
                System.out.println (rs.getString ( "ename" )); 
            } 

        } the catch (a ClassNotFoundException E) { 
            e.printStackTrace (); 
        }catch (SQLException e) {
            e.printStackTrace();
        } finally{
            //6:关闭流
            try {
                if(rs != null){
                    rs.close();
                }

                if(stm != null){
                    stm.close();
                }

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

 

  

Guess you like

Origin www.cnblogs.com/liangxiaojin/p/12445601.html