• JDBC全解析


    好久没用JDBC了,都有点忘了。昨天晚上系统的总结了下

    包括对结果集的指针的操作,批处理,存储过程的操作等等

      1 package com.jdbc;
      2 
      3 import java.sql.CallableStatement;
      4 import java.sql.Connection;
      5 import java.sql.DatabaseMetaData;
      6 import java.sql.DriverManager;
      7 import java.sql.PreparedStatement;
      8 import java.sql.ResultSet;
      9 import java.sql.ResultSetMetaData;
     10 import java.sql.SQLException;
     11 import java.sql.Statement;
     12 
     13 import com.jdbc.entity.Courseinfo;
     14 
     15 public class OralceConnTest {
     16     private String url="jdbc:oracle:thin:@localhost:1521:ibn";
     17     private String user="test";
     18     private String pwd="abs";
     19     private Connection conn;
     20     private Statement stat;
     21     private PreparedStatement ps;
     22     private ResultSet rs;
     23     private CallableStatement cs;
     24     /**
     25      * 关闭连接 关闭语句对象 关闭结果集
     26      * 注意Statement和PreparedStatement的区别
     27      * @param args
     28      * @throws SQLException
     29      * @throws InstantiationException
     30      * @throws IllegalAccessException
     31      * @throws ClassNotFoundException
     32      */
     33     public static void main(String[]args) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException{
     34         OralceConnTest cont=OralceConnTest.class.newInstance();
     35         cont.getConnection();
     36         cont.callStatement();
     37 //        Courseinfo course=new Courseinfo();
     38 //        course.setId(5);
     39 //        course.setUsername("小明");
     40 //        course.setPassword("456");
     41 //        cont.insert(course);
     42     }
     43     /**
     44      * 加载驱动,建立连接
     45      * @return
     46      */
     47     public Connection getConnection(){
     48         try {
     49             Class.forName("oracle.jdbc.driver.OracleDriver");
     50             conn=DriverManager.getConnection(url, user, pwd);
     51         } catch (Exception e) {
     52             e.printStackTrace();
     53         }
     54         return conn;
     55     }
     56     /**
     57      *查询数据库的表 
     58      * @throws SQLException
     59      * @throws ClassNotFoundException
     60      */
     61     public void conn() throws SQLException, ClassNotFoundException{
     62         try {
     63             stat=conn.createStatement();
     64             ResultSet rs=stat.executeQuery("select userid,username,password from userinfo");
     65             while(rs.next()){
     66                 StringBuffer sb=new StringBuffer();
     67                 String a=rs.getString(1);
     68                 String b=rs.getString(2);
     69                 String c=rs.getString(3);
     70                 sb.append(a).append(b).append(c);
     71                 System.out.println(sb);
     72             }
     73         } catch (SQLException e) {
     74             e.printStackTrace();
     75         }finally{
     76             conn.close();
     77             stat.close();
     78         }
     79     }
     80     /**
     81      * 执行插入操作 注意插入操作 insert into tablename values(id,'name','password') 注意这个单引号不能忘掉
     82      * @param course
     83      */
     84     public void insert(Courseinfo course){
     85         try {
     86             //将自动提交事务设关闭
     87             conn.setAutoCommit(false);
     88             stat=conn.createStatement();
     89             String sql="insert into userinfo(userid,username,password)" +
     90             "values("+course.getId()+",'"
     91             +course.getUsername()+"','"+course.getPassword()+"')";
     92             int a=stat.executeUpdate(sql);
     93             if(a==1){
     94                 System.out.println("statement插入正常");
     95                 //事务提交
     96                 conn.commit();
     97             }else{
     98                 //事务回滚
     99                 conn.rollback();
    100             }
    101             //将事务自动提交恢复
    102             conn.setAutoCommit(true);
    103         } catch (SQLException e) {
    104             // TODO Auto-generated catch block
    105             e.printStackTrace();
    106         }finally{
    107 
    108             if(stat!=null){
    109                 try {
    110                     stat.close();
    111                 } catch (SQLException e) {
    112                     // TODO Auto-generated catch block
    113                     e.printStackTrace();
    114                 }
    115             }
    116             if(conn!=null){
    117                 try {
    118                     conn.close();
    119                 } catch (SQLException e) {
    120                     // TODO Auto-generated catch block
    121                     e.printStackTrace();
    122                 }
    123             }
    124         }
    125     }
    126     /**
    127      * statement每次执行sql语句,相关数据库都要执行sql语句的编译
    128      * preparedstatement是预编译得,   preparedstatement支持批处理
    129      * statement执行update必须有参数
    130      * preparedStatement在创建时已经预编译了,没有参数
    131      * @param course
    132      */
    133     public void prepareInsert(Courseinfo course){
    134 
    135         try {
    136             String sql="insert into userinfo(userid,username,password)values(?,?,?)";
    137             ps=conn.prepareStatement(sql);
    138             ps.setInt(1, course.getId());
    139             ps.setString(2, course.getUsername());
    140             ps.setString(3, course.getPassword());
    141             int a=ps.executeUpdate();
    142             if(a==1){
    143                 System.out.println("preparedStatementd插入正常");
    144             }
    145         } catch (SQLException e) {
    146             // TODO Auto-generated catch block
    147             e.printStackTrace();
    148         }finally{
    149             if(ps!=null){
    150                 try {
    151                     ps.close();
    152                 } catch (SQLException e) {
    153                     // TODO Auto-generated catch block
    154                     e.printStackTrace();
    155                 }
    156             }
    157             if(conn!=null){
    158                 try {
    159                     conn.close();
    160                 } catch (SQLException e) {
    161                     // TODO Auto-generated catch block
    162                     e.printStackTrace();
    163                 }
    164             }
    165         }
    166     
    167     }
    168     /**
    169      * 获取数据库基本信息
    170      */
    171     public void getDbData(String tablename){
    172         String sql="select*from "+tablename;
    173         try {
    174             //获取数据库元数据
    175             DatabaseMetaData dmd=conn.getMetaData();
    176             //获取数据库的各种信息   数据库名字
    177             System.out.println(dmd.getDatabaseProductName());
    178             stat=conn.createStatement();
    179             rs=stat.executeQuery(sql);
    180             //结果集元数据
    181             ResultSetMetaData rmd=rs.getMetaData();
    182             //获取结果集列数
    183             int columnCount=rmd.getColumnCount();
    184             for(int i=0;i<columnCount;i++){
    185                 //获取列名
    186                 System.out.println(rmd.getColumnName(i));
    187             }
    188             while(rs.next()){
    189                 for(int i=0;i<columnCount;i++){
    190                     //由列名获取结果集
    191                     String value=rs.getString(rmd.getColumnName(i));
    192                 }
    193             }
    194         } catch (SQLException e) {
    195             e.printStackTrace();
    196         }
    197     }
    198     /**
    199      * 批处理
    200      */
    201     public void batchExecute(){
    202         String sql="insert into courseinfo(userid) values(?)";
    203         try {
    204             conn.setAutoCommit(false);
    205             ps=conn.prepareStatement(sql);
    206             for(int i=5;i<100;i++){
    207                 ps.setInt(1, i);
    208                 //将sql语句加入批处理
    209                 ps.addBatch();
    210                 //每10条处理一次
    211                 if(i%10==0){
    212                     stat.executeBatch();
    213                     stat.clearBatch();
    214                 }
    215                 stat.executeBatch();//处理最后五条
    216             }
    217         } catch (SQLException e) {
    218             // TODO Auto-generated catch block
    219             e.printStackTrace();
    220         }
    221         
    222     }
    223     /**
    224      * 操作结果集
    225      *基于缓存的分页策略
    226      *起始数据 (page-1)*pageSize+1
    227      * @param pageSize 每页有多少条数据
    228      * @param page 第几页
    229      */
    230     public void bufferPageDemo(int pageSize,int page){
    231         String sql="select*from courseinfo";
    232         try {
    233             //结果集滚动不敏感的(可跳步的)
    234             /**
    235              * ResultSet有个结果集指针,初始是指向第一个结果的
    236              * 
    237              * 1.ResultSet.TYPE_FORWARD_ONLY 指针只能安装列顺序向前移动,也就是说在取得name列之后,将不能再返回获取id列的值;
    238              * 2.ResultSet.TYPE_SCROLL_INSENSITIVE指针可以前后移动,INSENSITIVE表示不及时更新,就是如果数据库里的数据修改过,并不在ResultSet中反映出来;
    239              * 3.ResultSet.TYPE_SCROLL_SENSITIVE指针可以前后移动,SENSITIVE表示及时跟踪数据库的更新,以便更改ResultSet中的数据。
    240              * 
    241              * 
    242              * 1.ResultSet.CONCUR_READ_ONLY表示当前ResultSet对象只读, 不能用结果集更新数据库中的表
    243              * 2.ResultSet.CONCUR_UPDATABLE表示当前ResultSet能用结果集更新数据库中的表
    244              * 
    245              * ResultSet提供各种控制指针的方法
    246              */
    247             //conn.createStatement(resultSetType, resultSetConcurrency)
    248             stat=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
    249                     ResultSet.CONCUR_UPDATABLE);
    250             rs=stat.executeQuery(sql);
    251             rs.last();//移动到最后一行
    252             int rownum=rs.getRow();//记录当前的行号,记录的条数
    253             rs.absolute(1);//将指针移到第一行
    254             rs.relative(2);//相对当前位置移动2行
    255             /*更新第三条记录*/
    256             rs.updateInt(1, 100);
    257             rs.updateString(2, "更新地方");
    258             rs.updateRow();//更新数据源的数据
    259             /*插入数据*/
    260             rs.moveToInsertRow();//指针移到插入行
    261             rs.updateInt(1, 100);
    262             rs.updateString(2, "插入地方");
    263             rs.insertRow();
    264             rs.moveToCurrentRow();//指针移到插入前的位置
    265         } catch (SQLException e) {
    266             // TODO Auto-generated catch block
    267             e.printStackTrace();
    268         }
    269     }
    270     /**
    271      * 存储过程的调用
    272      * 
    273      * 
    274      */
    275     public void callStatement(){
    276         StringBuffer sb=new StringBuffer(20);//线程安全
    277         /*
    278          * sys_refcursor游标类型
    279           create or replace procedure testc(infos out sys_refcursor,num out number,names  out varchar2)
    280             is
    281             begin
    282             open infos for 'select*from userinfo';
    283             select count(*) into num from userinfo;
    284             select username into names from userinfo where userid=1;
    285             end testc;
    286          */
    287         sb.append("{call testc(?,?,?)}");
    288         try {
    289             cs=conn.prepareCall(sb.toString());
    290             //返回游标类型
    291             cs.registerOutParameter(1, oracle.jdbc.OracleTypes.CURSOR);
    292             //返回num类型
    293             cs.registerOutParameter(2, java.sql.Types.INTEGER);
    294             //返回字符类型
    295             cs.registerOutParameter(3, java.sql.Types.VARCHAR);
    296             cs.execute();
    297             rs=(ResultSet)cs.getObject(1);
    298             //获取结果集的列数
    299             int count=rs.getMetaData().getColumnCount();//获得结果集记录的字段数
    300             System.out.println("count="+count);
    301             while(rs.next()){
    302                 for(int i=1;i<=count;i++){
    303                     System.out.println(rs.getString(i));
    304                 }
    305             }
    306             System.out.println("------返回number类型-------");
    307             int counts=cs.getInt(2);
    308             System.out.println(counts);
    309             System.out.println("-----返回varchar-------");
    310             String name=cs.getString(3);
    311             System.out.println(name);
    312         } catch (SQLException e) {
    313             // TODO Auto-generated catch block
    314             e.printStackTrace();
    315         }
    316         /*调用存储过程,返回游标,整数,字符串*/
    317         
    318         /*调用存储过程,返回整数*/
    319         /**/
    320         /**/
    321         
    322     }
    323 }
  • 相关阅读:
    高性能 HTML5 地铁样式的应用程序中的内容
    微软披露更多ARM Win8细节
    下一代互联网搜索的前沿:意图、知识与云
    使用 Sphinx 更好地进行 MySQL 搜索使用 Sphinx 进行非全文本搜索
    如何加快数模计算以及如何解决数模计算的收敛性问题
    Google App Engine正式支持Python 2.7
    ASP.NET MVC模型绑定
    给 MySQL 增加 Sequence 管理功能
    使用 Rational Build Forge 自动化 IBM Cloud 上的构建和发布过程
    Windows Phone 8基于WinRT?
  • 原文地址:https://www.cnblogs.com/javahuang/p/3156218.html
Copyright © 2020-2023  润新知