JDBC_上课自己的代码

第一天
连接Oracle
package tarena;
import java.sql.*;
public class lab1 {
    public static void main(String[] args) {
        Connection con = null;
        try {
            // 加载驱动
            String driverName = "oracle.jdbc.driver.OracleDriver";
            Class.forName(driverName);
            // 建立数据库连接
            String url = "jdbc:oracle:thin:@192.168.7.88" + ":1521:tarena";
            String username = "rensx";
            String pwd = "rensx";
            con = DriverManager.getConnection(url, username, pwd);
            System.out.println("con->" + con);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
/////////////////////////////////////////////////////////////////
连接MySQL
package tarena;
import java.sql.*;
public class lab1 {
    public static void main(String[] args) {
        Connection con = null;
        try {
            // 加载驱动
            String driverName = "com.mysql.jdbc.Driver";
            Class.forName(driverName);
            // 建立数据库连接
            String url = "jdbc:mysql://127.0.0.1:3306/mydb";
            String username = "root";
            String pwd = "";
            con = DriverManager.getConnection(url, username, pwd);
            System.out.println("con->" + con);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
con->com.mysql.jdbc.Connection@ae506e
////////////////////////////////////////////////
能用
package tarena;
import java.sql.*;
public class lab4{
    public static void main(String[] args) {
        Connection con = null;
        Statement stmt = null;
        ResultSet re = null;
        try {    //1加载驱动        
            String driverName = "oracle.jdbc.driver.OracleDriver";
            Class.forName(driverName);
            //2建立数据库连接
            String url = "jdbc:oracle:thin:@192.168.7.88" + ":1521:tarena";
            String username = "rensx";
            String pwd = "rensx";
            con = DriverManager.getConnection(url, username, pwd);
            //3获取数据库操纵对象
            stmt =con.createStatement();
            //4SQL语句
            String sql= "drop table ren_sql";
            stmt.executeUpdate(sql);/**executeUpdate执行给定 SQL 语句,该语句可能为 INSERT、UPDATE 或 DELETE 语句,或者不返回任何内容的 SQL 语句(如 SQL DDL 语句)*/
            sql= "create table ren_sql(name varchar2(20),id number(10)  )";
            stmt.executeUpdate(sql);
            sql="insert into ren_sql values('ren1',20)";
            stmt.executeUpdate(sql);
            sql="insert into ren_sql values('ren2',20)";
            stmt.executeUpdate(sql);
            sql="insert into ren_sql values('ren3',20)";
            stmt.executeUpdate(sql);
            sql="select * from ren_sql";
            re=stmt.executeQuery(sql);//executeQuery执行给定的 SQL 语句,该语句返回单个 ResultSet 对象
            System.out.println("re->"+re);

            //5处理结果集
            StringBuffer sb=new StringBuffer();
            while(re.next()){
            sb.append("name:"+re.getString(1)+" ");
            sb.append("id:"+re.getInt(2)+"\n");
            }
            System.out.println(sb);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //6用完就可以关 
            try {
                if(re!=null)re.close();//次序不能换
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if(stmt!=null)stmt.close();//次序不能换
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if(con!=null)con.close();//次序不能换
            } catch (Exception e) {
                e.printStackTrace();
            }
        }//finally
    }
}
//////////////////////////////////////////////////
第二天
工具类

package tarena;
import java.sql.*;
public class JdbcUtil{
    static {            
        try{
                String driverName="oracle.jdbc.driver.OracleDriver";
        Class.forName(driverName);}catch(Exception e){e.printStackTrace();}
         }//static

    public static Connection getConnection(){
        String url = "jdbc:oracle:thin:@192.168.7.88" + ":1521:tarena";
        String username = "rensx";
        String pwd = "rensx";
        Connection con=null;
        try{
            con = DriverManager.getConnection(url, username, pwd);
        }catch(Exception e){e.printStackTrace();}
        return con;
        
    }

    public static void release(ResultSet rs,Statement stmt,Connection con){
            try{if(rs!=null){rs.close();}}catch(Exception e){e.printStackTrace();}
        try{if(stmt!=null){stmt.close();}}catch(Exception e){e.printStackTrace();}
        try{if(con!=null){con.close();}}catch(Exception e){e.printStackTrace();}
    }
    public static void release(Object obj){
            try{if(obj instanceof ResultSet){((ResultSet)obj).close();}
        else if(obj instanceof Statement){((Statement)obj).close();}
        else if(obj instanceof Connection){((Connection)obj).close();}
        }catch(Exception e){e.printStackTrace();}
    }

    public static void resultSetMD(ResultSet rs) {//重要 
      // public static void printRs(ResultSet rs){
      if(rs==null){
        System.out.println("ResultSet is null!");
        return;
      }
      try{
        ResultSetMetaData md = rs.getMetaData();    
         int cols = md.getColumnCount();
        StringBuffer sb = new StringBuffer();
        while(rs.next()){
          for(int i=1;i<=cols;i++){
            sb.append(md.getColumnName(i)+"=");
            sb.append(rs.getString(i)+"  ");
          }
          sb.append("\n");
        }
        System.out.println(sb.toString());
      }catch(Exception e){
        e.printStackTrace();
      }
    
    }
} 
////////////////////////////////////////////////
 PreparedStatement的使用
package tarena;
import java.sql.*;
public class lab6{
    public static void main(String [] args){
        Connection con=null;
        PreparedStatement ps=null;
        ResultSet re = null;
        try{
        con = JdbcUtil.getConnection();

        String sql="insert into ren_sql values(?,?)";
        ps=con.prepareStatement(sql);
        for(int i=0;i<10;i++){ps.setString(1,"ren"+i);ps.setInt(2,i);ps.executeUpdate();}
        JdbcUtil.release(ps);//注意释放

        sql="select * from ren_sql";
        ps=con.prepareStatement(sql);
        re=ps.executeQuery();

        StringBuffer sb=new StringBuffer();
        while(re.next()){
        sb.append("name:"+re.getString(1)+"  ");
        sb.append("is:"+re.getString(2)+"\n");
        }
        System.out.println(sb);

        }catch(Exception e){}
        finally{JdbcUtil.release(re,ps,con);}
    }

}
////////////////////////////////////////////
 ResultSetMetaData的使用
package tarena;
import java.sql.*;
public class lab7{
    public static void main(String [] args){
        if(args.length!=1){System.out.println("error");return ;}

        String tableName=args[0];
        

        Connection con=null;
        PreparedStatement ps=null;
        ResultSet re = null;
        try{
        con = JdbcUtil.getConnection();

        String sql="select * from "+tableName;
        ps=con.prepareStatement(sql);
        re=ps.executeQuery();

        StringBuffer sb=new StringBuffer();
        ResultSetMetaData md =re.getMetaData();
        int cols =md.getColumnCount();
        System.out.println("cols:"+cols);
        for(int i=1;i<=cols;i++){
            sb.append(md.getColumnName(i)+"->");
            sb.append(md.getColumnType(i)+"&");//类型编号
            sb.append(md.getColumnTypeName(i)+"\n");//字段类型名字
        }

        sb.append("\n\n");
        while(re.next()){
        for(int i=1;i<=cols;i++){
            sb.append(md.getColumnName(i)+"=");
            sb.append(re.getString(i));
            sb.append("   ");
            }
        sb.append("\n");
        }
        System.out.println(sb);

        }catch(Exception e){}
        finally{JdbcUtil.release(re,ps,con);}
    }

}
////////////////////////////////////////////////
DatabaseMetaData的使用
package tarena;
import java.sql.*;
public class Lab9
{
    public static void main(String[] args){
      Connection con = null;
      ResultSet rs =null;
      try{
        con = JdbcUtil.getConnection();
        DatabaseMetaData md = con.getMetaData();
        String[] types = {"TABLE"};
        rs = md.getTables(
                null,
                "OPENLAB",
                "%",
                types);
        JdbcUtil.printRs(rs);
      }catch(Exception e){
        e.printStackTrace();
      }finally{
        JdbcUtil.release(rs,null,con);
      }
    }
}
///////////////////////////////////////////////
package tarena;
import java.sql.*;
import java.io.*;

public class SQLTools
{
    public static void main(String[] args){
      Connection con = null;
      while((con=getConnection())==null){}
      try{
        StringBuffer sb = new StringBuffer();
        String cmd = "";
        boolean flag = true;
        int c = 0;
        String message = "";
        while(flag){
          if(c++==0){
            message = "SQLTools->";
          }else{
            message = c+"->";
          }
          sb.append(prompt(message));
          cmd = sb.toString().trim();
          if(cmd.endsWith(";")){
            String sql = cmd.substring(0,cmd.length()-1);
            if("quit".equals(sql)){
               flag = false;
            }else{
               System.out.println(sql);
               execute(sql,con);
               sb = new StringBuffer();
               c=0;
            }
          }
        }
      }catch(Exception e){
        e.printStackTrace();
      }finally{
        JdbcUtil.release(con);
      }
    }
    public static Connection getConnection(){
        try{
            String driverName="oracle.jdbc.driver.OracleDriver";
            Class.forName(driverName);}catch(Exception e){e.printStackTrace();}
      String message="请输入url:\n";
      String url = prompt(message);
      message = "请输入用户名:\n";
      String username = prompt(message);
      message = "请输入密码:\n";
      String pwd = prompt(message);
      Connection con = null;
      try{
        con = DriverManager.getConnection(
            url,username,pwd);
      }catch(Exception e){
        System.out.println("->连接失败!");
      }
      return con;
    
    }
    public static String prompt(String message){
      BufferedReader in = 
          new BufferedReader(
            new InputStreamReader(System.in));
      System.out.print(message);
      String input = "";
      try{
        input=in.readLine();
      }catch(Exception e){
        e.printStackTrace();
      }
      return input;
    }
    public static void execute(String sql,Connection con){
      Statement stmt = null;
      ResultSet rs = null;
      int c = 0;
      try{
        stmt = con.createStatement();
        if(stmt.execute(sql)){
          rs = stmt.getResultSet();
          JdbcUtil.resultSetMD(rs);
        }else{
          c = stmt.getUpdateCount();
          System.out.println("更新成功-"+c);
        }
      }catch(Exception e){
        System.out.println("数据库操作失败!");
      }finally{
        JdbcUtil.release(rs,stmt,null);
      }
      
    }
}
////////////////////////////////////////////////

package tarena;

import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class ConnectionFactory {
    private static String url;
    private static String userName;
    private static String passwd;
    private static String driver;

    static {

        try {
            parseConfig();
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static synchronized Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,userName,passwd);
    }
    private static void parseConfig() throws FileNotFoundException {
        SAXBuilder builder = new SAXBuilder();
        Document dom = null;
        try {
            dom = builder.build("dbconfig.xml");

        } catch (Exception e) {
            throw new FileNotFoundException("file");
        }
        Element root = dom.getRootElement();
        String use = root.getAttributeValue("use");
        List<Element> infos = root.getChildren();
        for (Element info : infos) {
            if (use.equals(info.getAttributeValue("name"))) {
                List<Element> values = info.getChildren();
                for (Element value : values) {
                    if ("url".equals(value.getName())) {
                        url = value.getTextTrim();
                    } else if ("username".equals(value.getName())) {
                        userName = value.getTextTrim();
                    } else if ("passwd".equals(value.getName())) {
                        passwd = value.getTextTrim();
                    } else if ("driver".equals(value.getName())) {
                        driver = value.getTextTrim();
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        new ConnectionFactory();
    }
}
/**
 * <?xml version="1.0" encoding="UTF-8"?>
<dbconfig use="oracle">
    <dbinfo name="oracle">
        <url>jdbc:oracle:thin:@192.168.7.88:1521:tarena</url>
        <username>rensx</username>
        <passwd>rensx</passwd>
        <driver>oracle.jdbc.driver.OracleDriver</driver>
    </dbinfo>
    <dbinfo name="mysql">
        <url>jdbc:mysql://127.0.0.1:3306/test</url>
        <username>root</username>
        <passwd></passwd>
        <driver>com.mysql.jdbc.Driver</driver>
    </dbinfo>
</dbconfig>*/
///////////////////////////////////////////////////////////
第3天
package tarena;
import java.sql.*;
import java.io.*;

public class SQLTools
{   //添加的事务的处理功能
    public static void main(String[] args){
        
      Connection con = null;
      while((con=getConnection())==null){}
      try{
          //自动提交关闭
          con.setAutoCommit(false);
        StringBuffer sb = new StringBuffer();
        String cmd = "";
        boolean flag = true;
        int c = 0;
        String message = "";
        while(flag){
          if(c++==0){
            message = "SQLTools->";
          }else{
            message = c+"->";
          }
          sb.append(prompt(message));
          cmd = sb.toString().trim();
          if(cmd.endsWith(";")){
            String sql = cmd.substring(0,cmd.length()-1);//去分号的作用
            if("quit".equals(sql)){
               flag = false;
               con.commit();//
            }else if("commit".equals(sql)){
                con.commit();
                c=0;
            }else if("roolback".equals(sql)){
                con.rollback();
                c=0;
            }else{
               System.out.println(sql);
              
               try{ execute(sql,con);}catch(Exception e){
                   System.out.println("强制回滚");
                   try{
                        if(con!=null){con.rollback();}
                    }catch(Exception ee){}
               }
               sb = new StringBuffer();
               c=0;
            }
          }
        }
      }catch(Exception e){
        e.printStackTrace();
       
      }finally{
        JdbcUtil.release(con);
      }
    }
    public static Connection getConnection(){
        try{
            String driverName="oracle.jdbc.driver.OracleDriver";
            Class.forName(driverName);}catch(Exception e){e.printStackTrace();}
      String message="请输入url:\n";
      String url = prompt(message);
      message = "请输入用户名:\n";
      String username = prompt(message);
      message = "请输入密码:\n";
      String pwd = prompt(message);
      Connection con = null;
      try{
        con = DriverManager.getConnection(
            url,username,pwd);
      }catch(Exception e){
        System.out.println("->连接失败!");
      }
      return con;
    
    }
    public static String prompt(String message){
      BufferedReader in = 
          new BufferedReader(
            new InputStreamReader(System.in));
      System.out.print(message);
      String input = "";
      try{
        input=in.readLine();
      }catch(Exception e){
        e.printStackTrace();
      }
      return input;
    }
    public static void execute(String sql,Connection con) throws Exception{
      Statement stmt = null;
      ResultSet rs = null;
      int c = 0;
      try{
        stmt = con.createStatement();
        if(stmt.execute(sql)){
          rs = stmt.getResultSet();
          JdbcUtil.resultSetMD(rs);
        }else{
          c = stmt.getUpdateCount();
          System.out.println("更新成功-"+c);
        }
      }catch(Exception e){
        System.out.println("数据库操作失败!");
        throw e;
      }finally{
        JdbcUtil.release(rs,stmt,null);
      }
      
    }
}
/////////////////////////////////////////////////////////
事务的设置
public class lab10 {

    public static void main(String[] args) {
        Connection con =null;
        try{
            con=JdbcUtil.getConnection();
            con.setTransactionIsolation(Connection.TRANSACTION_NONE);
            //抛异常:java.sql.SQLException: 仅 READ_COMMITTED 和 SERIALIZABLE 是有效的事务处理级
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            JdbcUtil.release(con);
        }
    }
}

//////////////////////////////////////////
public class lab11 {
//JDBC2.0的结果集
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = JdbcUtil.getConnection();
            con.setAutoCommit(false);//习惯
            String sql = "select * from ren_sql";
            //
            ps = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);
            
            rs = ps.executeQuery();
            JdbcUtil.resultSetMD(rs);
            if(rs.isAfterLast()){
                System.out.println("游标在最后面");
                rs.beforeFirst();
            }
            JdbcUtil.resultSetMD(rs);
            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try{
                if(con!=null){con.rollback();}
            }catch(Exception ee){}
        }finally{
            JdbcUtil.release(rs, ps, con);
        }

    }

}
////////////////////////////////////////////
public class lab12 {
//JDBC2.0的结果集更新
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = JdbcUtil.getConnection();
            con.setAutoCommit(false);//习惯
            String sql = "select id,mon from ren_bank";//不能用* 来表示
            //
            ps = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);        
            rs = ps.executeQuery();            
            //
            rs.moveToInsertRow();
            rs.updateInt(1,3);
            rs.updateDouble(2,100);
            rs.insertRow();
            rs.moveToCurrentRow();
            //
            System.out.println("*************1**********");
            JdbcUtil.resultSetMD(rs);
            con.commit();
            System.out.println("**************2***************");
            JdbcUtil.release(rs);
            rs=ps.executeQuery();
            JdbcUtil.resultSetMD(rs);
            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try{
                if(con!=null){con.rollback();}
            }catch(Exception ee){}
        }finally{
            JdbcUtil.release(rs, ps, con);
        }

    }

}
////////////////////////////////////////
package tarena;

import java.sql.*;
//改进版的
public class SQLTools { // 添加的事务的处理功能
    public static void main(String[] args) {

        Connection con = null;
        while ((con = getConnection()) == null) {
        }
        try {
            // 自动提交关闭
            con.setAutoCommit(false);
            StringBuffer sb = new StringBuffer();
            String cmd = "";
            boolean flag = true;
            int c = 0;
            String message = "";
            while (flag) {
                if (c++ == 0) {
                    message = "SQLTools->";
                } else {
                    message = c + "->";
                }
                sb.append(prompt(message));
                cmd = sb.toString().trim();
                if (cmd.endsWith(";")) {
                    String sql = cmd.substring(0, cmd.length() - 1);// 去分号的作用
                    if ("quit".equals(sql)) {
                        flag = false;
                        con.commit();//
                    } else if ("commit".equals(sql)) {
                        con.commit();
                        c = 0;
                    } else if ("roolback".equals(sql)) {
                        con.rollback();
                        c = 0;
                    } else {
                        System.out.println(sql);

                        try {
                            execute(sql, con);
                        } catch (Exception e) {
                            System.out.println("强制回滚");
                            try {
                                if (con != null) {
                                    con.rollback();
                                }
                            } catch (Exception ee) {
                            }
                        }
                        sb = new StringBuffer();
                        c = 0;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            JdbcUtil.release(con);
        }
    }

    public static Connection getConnection() {
        try {
            String driverName = "oracle.jdbc.driver.OracleDriver";
            Class.forName(driverName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String message = "请输入url:\n";
        String url = prompt(message);
        message = "请输入用户名:\n";
        String username = prompt(message);
        message = "请输入密码:\n";
        String pwd = prompt(message);
        Connection con = null;
        try {
            con = DriverManager.getConnection(url, username, pwd);
        } catch (Exception e) {
            System.out.println("->连接失败!");
        }
        return con;

    }

    public static String prompt(String message) {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.print(message);
        String input = "";
        try {
            input = in.readLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return input;
    }

    public static void execute(String sql, Connection con) throws Exception {
        Statement stmt = null;
        ResultSet rs = null;
        int c = 0;
        try {
            stmt = con.createStatement();
            if (stmt.execute(sql)) {
                rs = stmt.getResultSet();
                JdbcUtil.resultSetMD(rs);
            } else {
                c = stmt.getUpdateCount();
                System.out.println("更新成功-" + c);
            }
        } catch (Exception e) {
            System.out.println("数据库操作失败!");
            throw e;
        } finally {
            JdbcUtil.release(rs, stmt, null);
        }

    }
}
///////////////////////////////////////
电子银行的代码  很重要
////////////////////////////////////
第4天
public class lab13 {
    // 批量更新
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = JdbcUtil.getConnection();
            con.setAutoCommit(false);
            String sql = "insert into ren_bank values(?,?)";
            ps = con.prepareStatement(sql);
            System.out.println("now=1" + new java.util.Date());

            for (int i = 0; i < 1000; i++) {
                ps.setInt(1, i);
                ps.setDouble(2, i);
                //ps.executeUpdate();
                //批量写法,每100个记录提交
                ps.addBatch();
                if(i%100==0){ps.executeBatch();}
            }
            con.commit();
            System.out.println("now=2" + new java.util.Date());
        } catch (Exception e) {
            e.printStackTrace();
            try {
                if (con != null)
                    con.rollback();
            } catch (Exception ee) {
            } finally {
                JdbcUtil.release(rs, ps, con);
            }
        }

    }

}
////////////////////////////////////////
Blob类的使用

数据的写
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class lab14 {
    // JDBC2.0 的大数据类型
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Blob b = null;
        int id = 1;

        String filename = args[0];//手动参数输入
        System.out.println("filename="+filename);
        try {
            con = JdbcUtil.getConnection();
            con.setAutoCommit(false);
            // 1委托oracle 数据库替我们制造一个空的blob字段
            String sql = "insert into ren_blob values(?,?,empty_blob())";// oracle
                                                                            // 特有函数
            ps = con.prepareStatement(sql);
            ps.setInt(1, id);
            ps.setString(2, filename);
            ps.executeUpdate();
            // 2将空的blob 字段值读回来 我们就可以有一个空的blob的对象实例
            sql = "select fileContent from ren_blob where id=? for update";// 更新锁
            JdbcUtil.release(ps);
            ps = con.prepareStatement(sql);
            ps.setInt(1, id);
            rs = ps.executeQuery();
            if (rs.next()) {
                b = rs.getBlob(1);
            }
            // 3将文件中的内容导入到blob对象中
            InputStream in = new FileInputStream(filename);
            OutputStream out = b.setBinaryStream(0);
            byte[] content = new byte[in.available()];
            in.read(content);
            out.write(content);
            in.close();
            out.close();
            // 4将blob对象更新到数据库
            sql = "update ren_blob set fileContent=? where id=?";
            JdbcUtil.release(rs, ps, null);
            ps = con.prepareStatement(sql);
            ps.setBlob(1, b);
            ps.setInt(2, id);
            ps.executeUpdate();
            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                if (con != null)
                    con.rollback();
            } catch (Exception ee) {
            }

        } finally {
            JdbcUtil.release(null, ps, con);
        }
    }

}
/**
 * create table ren_blob( id number(12) primary key, filename varchar(55) not
 * null, fileContent blob );
 */


数据的读
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class lab142 {

    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Blob b = null;
        int id = 1;
        String filename = args[0];// 手动参数输入
        if (args.length != 1) {
            System.out.println("文件名");
        }
        try {
            con = JdbcUtil.getConnection();
            con.setAutoCommit(false);
            // 1读特定id的blob字段
            String sql = "select fileContent from ren_blob where id=? for update";
            ps = con.prepareStatement(sql);
            ps.setInt(1, id);
            rs = ps.executeQuery();
            if (rs.next()) {
                b = rs.getBlob(1);
            }
            // 2将blob对象的数据导入文件(从数据库到文件)
            InputStream in = b.getBinaryStream();
            OutputStream out = new FileOutputStream(filename);
            // error:byte[] content=new byte [in.available()];
            int b2 = 0, c = 0;
            while ((b2 = in.read()) != -1) {
                out.write(b2);
                if (++c % 1024 == 0) {
                    System.out.println("读了");
                }
            }
            in.close();
            out.close();
            con.commit();

        } catch (Exception e) {
            e.printStackTrace();
            try {
                if (con != null)
                    con.rollback();
            } catch (Exception ee) {
            }

        } finally {
            JdbcUtil.release(rs, ps, con);
        }

    }

}
/////////////////////////////////////////////////////////////

 

你可能感兴趣的:(oracle,sql,c,mysql,jdbc)