加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

jdbc 使用PreparedStatement来存储和读取大数据(Blob或Clob)

发布时间:2020-12-14 23:23:25 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 //假设这里建立的数据库位use,而建立的表位luserimport java.io.*;import java.sql.*;public class DBB{private static String driver ="com.mysql.jd

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

//假设这里建立的数据库位use,而建立的表位luser

import  java.io.*;

import java.sql.*;

public class DBB{

private  static  String driver ="com.mysql.jdbc.driver";

private  static  String url ="jdbc:mysql://localhost:3306/use";
private static  String user="root";

private static String pass="admin";

public static  void main(String[]args){

Connection con= null;

PreparedStatement sta= null;

ResultSet res= null;

try{

//获取数据源

//假设就是从d盘中读取的一张照片;

File file= new File("d:" + File.separator + "photo.jpg");

int length= (int)file.length();

InputStream input = new FileInputStream(file);

//加载mysql驱动

Class.forName(driver);

//取得链接对象

con= DriverManager.getConnection(url,user,pass);

//取得操作对象

sta= con.prepareStatement("insert into luser values(?,?,?);");

//加载数据

sta.setInt(1,110);

sta.setString(2,"namefile");

sta.setBinaryStream(3,input,length);

sta.executeUpdate();

sta.clearParameters();

input.close();//释放资源;

}catch(SQLException e){

e.printStackTrace();

}catch(IOException e){

e.printStackTrace();

}catch(ClassNotFoundException e){
e.printStackTrace();
}

finally{

if(con!=null){

try{

con.close();

}catch(SQLException e){   //(_)%^&**(_)(&*)(*#%$%^&*(()__)(((

e.printStackTrace();

}

}

}

Statement stat= null;

try{

//数据的取得

stat= con.createStatement();

stat.executeQuery("select* from luser;");

res.next();

String filename= res.getString(2);

Blob blob= res.getBlob(3);

//把获得的数据写到指定的文件中

FileOutputStream out= new FileOutputStream("d:" + File.separator+ "dong" +".bak");

out.write(blob.getBytes(1,(int)blob.length()));

out.flush();//把内存中的东西刷出来

out.close();//释放资源

}catch(SQLException e){

e.printStackTrace();

}

catch(IOException e){

e.printStackTrace();

}

finally{

if(stat!= null){

try{

stat.close();

}catch(SQLException e){

e.printStackTrace();

}



}
if(con!=null){

try{

con.close();

}catch(SQLException e){

e.printStackTrace();

}

}

}

}

} 

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读