Java使用JDBC方式连接数据库

开发一个JDBC应用程序,基本需要以下几个步骤:

1.把JDBC驱动类装载入JAVA虚拟机中。使用java.lang.Class类的静态方法forName(String  className)实现。

2.加载驱动,并与数据库建立连接。DriverManager类跟着已注册的驱动程序,当我们调用getConnection()方法时,它会遍历驱动程序列表,直到匹配上一个能够连接至数据连接字符串中指定的数据库的驱动程序,加载此驱动程序后,使用DriverManager类的getConnection方法建立与数据库之间的连接。

例:

Connection con = DriverManager.getConnection(数据库连接字符串,数据库用户名,密码)

3.发送SQL语句并得到结果集。创建一个Statement接口的实例,并将SQL语句传递给它所连接的数据库。

 Statement实例分为3种类型:

 (1)执行静态SQL语句。通常通过Statement实例实现。

 (2)执行动态SQL语句。通常通过PreparedStatement实例实现。

 (3)执行数据库存储过程。通常通过CallableStatement实例实现。

例:

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from table1");

 Statement接口提供了三种执行SQL语句的方法:executeQuery 、executeUpdate ,execute 语句。

扫描二维码关注公众号,回复: 2042499 查看本文章
  1. ResultSet executeQuery(String sqlString):执行查询数据库的SQL语句 并返回一个结果集(ResultSet)对象。
  2. int executeUpdate(String sqlString):用于执行INSERT、UPDATE或DELETE语句以及SQL DDL语句,如:CREATE TABLE和DROP TABLE等 
  3. execute(sqlString):用于执行返回多个结果集、多个更新计数或二者组合的语句。

  例:

ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ;   
int rows = stmt.executeUpdate("INSERT INTO ...") ;   
boolean flag = stmt.execute(String sql) ;   

4.处理结果。处理结果分为两种情况:

(1)执行更新返回的是本次操作影响到的记录数。

 (2)  执行查询返回的结果是一个ResultSet对象。

例:

while(rs.next()){
         int x=rs.getInt("a");
         String s=rs.getString("b");
         float f=rs.getFloat("c");  
}

5.关闭JDBC对象

  操作完成后,要关闭所有使用的JDBC对象,以释放JDBC资源,关闭顺序和声明顺序相反。

 (1) 关闭记录集

 (2) 关闭声明

 (3) 关闭连接对象

 if(rs != null){   // 关闭记录集   
        try{   
            rs.close() ;   
        }catch(SQLException e){   
            e.printStackTrace() ;   
        }   
          }   
          if(stmt != null){   // 关闭声明   
        try{   
            stmt.close() ;   
        }catch(SQLException e){   
            e.printStackTrace() ;   
        }   
          }   
          if(conn != null){  // 关闭连接对象   
         try{   
            conn.close() ;   
         }catch(SQLException e){   
            e.printStackTrace() ;   
         }   
          }  

猜你喜欢

转载自www.linuxidc.com/Linux/2016-02/128328.htm