Java实现从数据库导出大量数据记录并保存到文件的方法
作者:5iasp 发布时间:2024-01-16 09:47:37
标签:Java,数据库,导出,保存
本文实例讲述了Java实现从数据库导出大量数据记录并保存到文件的方法。分享给大家供大家参考,具体如下:
数据库脚本:
-- Table "t_test" DDL
CREATE TABLE `t_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) DEFAULT NULL,
`createTime` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
代码:
package com.yanek.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
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 TestDB {
public static void main(String[] args) {
Test(); // 生成测试数据
//Exp();
//Exp(0);
//System.out.println(readText("/opt/id.txt"));
}
/**
* 导出数据
*/
public static void Exp() {
Connection Conn=null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String jdbcUrl = "jdbc:mysql://127.0.0.1:3306/testcms?characterEncoding=GBK";
String jdbcUsername = "root";
String jdbcPassword = "root";
Conn = DriverManager.getConnection(jdbcUrl, jdbcUsername, jdbcPassword);
System.out.println("conn"+Conn);
Exp(Conn);
} catch (SQLException e) {
e.printStackTrace();
}
catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
Conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void Exp(int startid) {
Connection Conn=null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String jdbcUrl = "jdbc:mysql://127.0.0.1:3306/testcms?characterEncoding=GBK";
String jdbcUsername = "root";
String jdbcPassword = "root";
Conn = DriverManager.getConnection(jdbcUrl, jdbcUsername, jdbcPassword);
System.out.println("conn"+Conn);
Exp(Conn,startid);
} catch (SQLException e) {
e.printStackTrace();
}
catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
Conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 导出从startid开始的数据
* @param conn
* @param start_id
*/
public static void Exp(Connection conn,int start_id) {
int counter = 0;
int startid=start_id;
boolean flag = true;
while (flag) {
flag = false;
String Sql = "SELECT * FROM t_test WHERE id>"
+ startid + " order by id asc LIMIT 50";
System.out.println("sql===" + Sql);
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(Sql);
while (rs.next()) {
flag = true;
int id = rs.getInt("id");
String title = rs.getString("title");
startid = id ;
counter++;
writeContent(counter+"--id--"+id+"--title-"+title+"\r\n", "/opt/","log.txt",true);
System.out.println("i="+counter+"--id--"+id+"--title-"+title);
}
rs.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
writeContent(""+startid, "/opt/","id.txt",false);
}
/**
* 导出一小时内的数据
* @param conn
*/
public static void Exp(Connection conn) {
int counter = 0;
//一小时内的数据
Long timestamp = System.currentTimeMillis() - (60 * 60 * 1000);
boolean flag = true;
while (flag) {
flag = false;
String Sql = "SELECT * FROM t_test WHERE createTime>"
+ timestamp + " LIMIT 50";
System.out.println("sql===" + Sql);
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(Sql);
while (rs.next()) {
flag = true;
int id = rs.getInt("id");
String title = rs.getString("title");
Long lastmodifytime = rs.getLong("createTime");
timestamp = lastmodifytime;
counter++;
System.out.println("i="+counter+"--id--"+id+"--title-"+title);
}
rs.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void Test() {
Connection Conn=null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String jdbcUrl = "jdbc:mysql://127.0.0.1:3306/testcms?characterEncoding=GBK";
String jdbcUsername = "root";
String jdbcPassword = "root";
Conn = DriverManager.getConnection(jdbcUrl, jdbcUsername, jdbcPassword);
System.out.println("conn"+Conn);
for(int i=1;i<=10000;i++)
{
add(Conn,"testTitle"+i+"-"+System.currentTimeMillis());
}
} catch (SQLException e) {
e.printStackTrace();
}
catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
Conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void add(Connection conn,String title)
{
PreparedStatement pstmt = null;
String insert_sql = "insert into t_test(title,createTime) values (?,?)";
System.out.println("sql="+insert_sql);
try {
pstmt = conn.prepareStatement(insert_sql);
pstmt.setString(1,title);
pstmt.setLong(2,System.currentTimeMillis());
int ret = pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 写入内容到文件
*
* @param number
* @param filename
* @return
*/
public static boolean writeContent(String c, String dirname,String filename,boolean isAppend) {
File f=new File(dirname);
if (!f.exists())
{
f.mkdirs();
}
try {
FileOutputStream fos = new FileOutputStream( dirname+File.separator+filename,isAppend);
OutputStreamWriter writer = new OutputStreamWriter(fos);
writer.write(c);
writer.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 从文件读取内容
*
* @param filename
* @return
*/
public static String readText(String filename) {
String content = "";
try {
File file = new File(filename);
if (file.exists()) {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String str = "";
String newline = "";
while ((str = br.readLine()) != null) {
content += newline + str;
newline = "\n";
}
br.close();
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
}
基本思想: 就是通过记录开始记录id,执行多次sql来处理. 由于大数据量所以不能使用一条sql语句来输出.否则会内存不足导致错误.
主要用途: 可以使用在做接口开发时,给第三方提供数据增量输出的场景使用.
希望本文所述对大家Java程序设计有所帮助。
0
投稿
猜你喜欢
- CUDACUDA是显卡厂商NVIDIA推出的运算平台。CUDA™是一种由NVIDIA推出的通用并行计算架构,是一种并行计
- Visual Studio作为宇宙最强IDE,目前已更新到2019版,启动界面变成如下样式。其中还集成最新的 python 3.7,以后用P
- 有个小项目,碰到需要批量建立输入框的需求,本文利用WxPython建立批量录入框窗口研究了一下WxPython ,实现了这个功能。# cod
- 预备知识点compile 函数 compile 函数用于编译正则表达式,生成一个正则表达式( Pattern )对象,供 match() 和
- 什么是RSS?RSS是站点用来和其他站点之间共享内容的一种简易方式(也叫聚合内容),通常被用于新闻和其他按顺序排列的网站,例如Blog。一段
- 简述由于某些原因,在使用 import 时,Python 找不到相应的模块。这时,解释器就会发牢骚 - ImportError。那么,Pyt
- 本文实例为大家分享了UDP实现文件传输的具体代码,供大家参考,具体内容如下tcp进行文件传输看这里–python实现TCP文件接发这里实现的
- Oracle数据库在使用的过程中常常会遇到这样或那样的问题,而这些问题常常又使我们感到很困惑,本文我们总结了Oracle数据库在使用过程中的
- 王者荣耀很多朋友都想买脚本和挂之类的,想更加容易的获得金币等可以在游戏里买英雄等,今天我们发挥程序员的优势教给大家用Python语言自己写一
- 耦合两个或以上的体系或两种运动形式间相互作用而彼此影响以至于联合起来的现象。在软件工程中,对象之间的耦合度就是对象之间的依赖性,对象之间的耦
- 第一步,下载PHPphp官网地址windows 下载直接解压即可liunx请自行csdn搜索教程第二步,下载code插件1. PHP Deb
- 在Python中创建进程有两种方式,第一种是:from multiprocessing import Processimport timed
- 第一步,修改工厂函数,配置邮件参数from flask import Flaskfrom config import Configfrom
- ----------记录一下这两天做的一个小demo功能是要实现一个从前端传给后端一张图片,在后端完成目标检测后,传给前端,前端接收后并展示
- 数据处理在现代企业运营中变得越来越重要,越来越关键,甚至会成为企业发展的一项瓶颈. 数据保护的重要性也不言而喻. 如果一个企业没有很好的数据
- 一、使用dotnet add package 命令行实现首先可以去这个网站:https://www.nuget.org/ 查找想要添加的引用
- 我们知道,一般的关系数据库(如SQL Server、Oracle、Access等)中的查询操作是支持集合操作的,例如可以用“Update A
- 前言开发过程中有时需要使用路径数据,虽然python有自己的svg或其他矢量库,但这里只是出于实验的目的,没必要深入研究,所以采用一些简单的
- 引用Nmap库实现扫描功能,本节课比较简单一看就会。编写环境:Python2.x编写:首先安装Nmap程序,并添加环境变量pip insta
- <!DOCTYPE html PUBLIC "-//W3C//DTD X