业务场景一
读取大量记录。如果查询过滤条件比较弱,一次读出较多的记录。获得的数据量很可能超过内存大小,出现内存溢出的异常。
为了解决上述问题,可以考虑使用游标。游标提供一种客户端读取部分结果集的机制。
业务场景二
读取表中的大字段 。如果表中包含数据量很大的字段,即使只读取 一条记录,也会超过内存大小,出现内存溢出的异常。
为了解决上述问题,可以考虑使用流读取和写入。
代码实例
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConnectionJDBC {
/**
* @param args
*/
//驱动程序就是之前在classpath中配置的JDBC的驱动程序的JAR 包中
public static final String DBDRIVER = "com.mysql.jdbc.Driver";
//连接地址是由各个数据库生产商单独提供的,所以需要单独记住
public static final String DBURL = "jdbc:mysql://192.168.0.4:3306/myDB?useCursorFetch=true";
//连接数据库的用户名
public static final String DBUSER = "root";
//连接数据库的密码
public static final String DBPASS = "";
//文件地址
public static final String FILEURL = "E:\\java.txt";
public static void main(String[] args) throws Exception {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
//1、加载数据库驱动程序
Class.forName(DBDRIVER);
//2、连接数据库
con = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
//3、创建Statement
stmt = con.prepareStatement("select * from person");
stmt.setFetchSize(1); //数据块的大小
//4、执行SQL语句
rs = stmt.executeQuery();
while(rs.next())
{
InputStream in = rs.getBinaryStream("address"); //流读取
File f= new File(FILEURL);
OutputStream out = new FileOutputStream(f,true);
int temp = 0;
while((temp = in.read()) != -1) //边读边写
{
out.write(temp);
}
in.close();
out.close();
}
}catch(SQLException e) {
//5、异常处理
}
finally {
//6、清理资源
if(con !=null)
{
con.close();
}
if(stmt!=null)
{
stmt.close();
}
if(rs!=null)
{
rs.close();
}
}
}
}